vba - 如何处理另一个工作簿的 Workbook_Open 事件中生成的错误?

标签 vba excel exception

我在同一文件夹中有两个工作簿:bkOpenErrorTest.xlsmbkOpenErrorTest_dict.xlsm .

bkOpenErrorTest_dict.xlsm ThisWorkbook中有以下代码模块:

Private Sub workbook_open()

Dim dict As Dictionary

Set dict = New Dictionary
dict.Add 0, 0
dict.Add 0, 0

End Sub

当通过双击文件名打开此工作簿时,它会抛出预期的未处理错误:

This key is already associated with an element of this collection

bkOpenErrorTest.xlsm Module1中有以下代码:

Sub testOpen()

Dim bk As Workbook

On Error GoTo errHandler

Workbooks.Open ThisWorkbook.Path & "\bkOpenErrorTest_dict.xlsm"

Exit Sub

errHandler:
Debug.Print "reached error handler"

End Sub

当错误捕获设置为 Break on Unhandled Errors 时,然后我运行 testOpen() ,当 bkOpenErrorTest_dict.xlsm 时仍会引发未处理的错误。打开。为什么 testOpen() 没有捕获到错误的错误处理程序?我该如何处理这个错误?我有一个应用程序,我想在一个文件夹中循环浏览许多工作簿,这些工作簿的 workbook_open() 中有这样的错误代码。事件,如果程序因此类未处理的错误而崩溃,我将无法迭代它们。

最佳答案

错误未被处理的原因是两个进程不在同一个线程中。如果您从主子过程调用“helper”子过程,则您将保留在同一线程中,并且“helper”中引发的错误将被主程序中的错误控制捕获。这类似于为什么 Application.Run 启动的过程中的错误不会抛出由启动它的过程中的错误控件处理的错误。

要对新打开的工作簿的 Workbook_Open 中发生的情况进行任何控制,您需要在应用程序实例级别进行控制。以下内容停止 Workbook_Open 事件过程的执行;如果不需要处理代码,那么这可能是您的解决方案。

Application.EnableEvents = False
Set bk = Workbooks.Open(ThisWorkbook.Path & "\bkOpenErrorTest_dict.xlsb")
Application.EnableEvents = True

如果字典填充是您试图克服的特定错误,请使用覆盖重复项的字典速记方法。

Dim dict As Dictionary

Set dict = New Dictionary
dict.Item(0) = 0
dict.Item(0) = 1
'dict.count = 1 with key as 0 and item as 1

更一般地说,您可以将潜在错误包装在 On Error Resume Next 和 On Error GoTo 0 中。

Dim dict As Dictionary

Set dict = New Dictionary
On Error Resume Next
dict.Add 0, 0
dict.Add 0, 1
On Error GoTo 0
'dict.count = 1 with key as 0 and item as 0

关于vba - 如何处理另一个工作簿的 Workbook_Open 事件中生成的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52122974/

相关文章:

VBA完整公式到单元格

python - Openpyxl:确定单元格值中的哪个字符是删除线

perl - 如何在 Perl 中创建和抛出异常?

excel - ActiveX 控件是否被禁用?

excel - 输入框运行时滚动

sql - 插入 INTO NOT EXISTS SQL Access

vba - 按下 'red x'时如何使Excel VBA中的用户窗体记住密码

excel - VBA 集合 - 将值从静态范围读入集合

c++ - 如何在 C++ 中抽象出重复的 try catch 模式

exception - 开发库时断言与异常