我有以下代码。但是错误没有得到处理
Sub Some_sub()
Some code here
On Error GoTo resumeCode
If Workbooks("Some file.xlsm").ReadOnly Then
GoTo readOnlyError
End If
resumeCode:
On Error GoTo fileNotOpen
Workbooks("Some file.xlsm").Activate
some more code here
Exit Sub
fileNotOpen:
MsgBox "Error: Claims followup.xlsm is not open." & Chr(10) & Chr(10) &
"Open the file in read/write"
Exit Sub
End Sub
当我运行调试模式时,它向我显示这一行:Workbooks("Some file.xlsm").Activate
黄色。而不是处理错误并转到标签。
在工具下的VBA中 - >选项 - > “常规”选项卡:“未处理的错误中断”处于活动状态。
当我打开文件时,它会运行代码。当它关闭时,它不会处理错误。
我做错了什么?
提前感谢您的帮助
答案 0 :(得分:1)
那就是它。正如我在评论中所说,当发生错误并处理错误时,在以任何方式明确调用On Error
关键字之前,您无法设置新的Resume
机制。
实现它的一种可能方法是,如果您不想更改例程的流程,只需在新的On Error
语句和Resume
之前添加标签。像这样,例如:
Sub Some_sub()
' Some code ...
On Error GoTo resumeCode
If Workbooks("Some file.xlsm").ReadOnly Then
GoTo readOnlyError
End If
' Some more code ...
resumeCode:
Resume ResumeHere ' <---------------------------------------- Invoke Resume
ResumeHere: ' <------------------------------------- Add some label
On Error GoTo fileNotOpen
Workbooks("Some file.xlsm").Activate
Exit Sub
fileNotOpen:
msgBox "Error: Claims followup.xlsm is not open." & Chr(10) & Chr(10) & "Open the file in read/write"
Exit Sub
End Sub
你应该小心,如果错误状态为空并且从正常流程到达,关键字Resume
本身会引发错误。在这种情况下,你应该把错误处理部分分开,你的日常工作结束,并从正常流程中的任何标签恢复。这通常是通常的做法。