Excel VBA error handling not working for second error

佐手、 提交于 2020-04-16 08:44:10

问题


In the below code Errorhandler correctly takes care of first error when I enter a workbook that is not open or any random string. But when I click on retry and again enter a random name I get "Subscript out of Range" error @ Workbooks(workbookname). Activate.

Can anyone help me why it is happening and how can I make it work. I have tried a lot of things. But nothing is working. This code is part of a larger program.

Sub test()

Dim workbkname As String
On Error GoTo Errorhandler
Retry:

workbookname = InputBox("Enter workbook name:", _
                        "Name Enrty")
If StrPtr(workbookname) = 0 Then
    MsgBox ("Aborting Program")
    End
End If

Workbooks(workbookname).Activate
Exit Sub

Errorhandler:
Response = MsgBox("Workbook " & workbookname & " not found", vbRetryCancel)
If Response = 4 Then
    GoTo Retry

End If

End Sub

回答1:


The issue here is that the VBA Error Handler does not clear the error once given a directive like GoTo. As a result, the code thinks that it has encountered an error within your error handling routine and thus throws the error up the stack.

In order to clear the error, you must either call Resume with a place to resume (either Resume alone to run the erroneous code again, Resume Next to resume the line of code following the error, or Resume can be called followed by a label, as below:

Sub ErrTest
    On Error Goto ErrHndl
    For i = 0 to 5
        a = 1/i
nextiLabel:
    Next i

    Exit Sub
ErrHndl:
    Resume nextiLabel
End Sub

You can also use Err.Clear() to remove the error, but that is less recommended.

See here for more info: Error Handling in Excel



来源:https://stackoverflow.com/questions/35929892/excel-vba-error-handling-not-working-for-second-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!