转到块不工作的VBA

总结 :我想做一些基本的error handling

问题 :当我遍历代码时,即使没有错误,我的“错误”块数据也会运行

– 我对VBA中的error handling相当陌生,不明白为什么Error块中的代码不在我指定的代码中进入块。 提前致谢!

代码

Function getReports() startJournal = Sheets("Runsheet").Range("B5") endJournal = Sheets("Runsheet").Range("E5") If startJournal = 0 Or endJournal = 0 Then GoTo Error End If 'bunch of code Error: MsgBox ("Error Statement") End Function 

错误标签之前需要Exit Function
即代码应该打标签(呃)只有在错误和退出的情况下,否则。

 Function getReports() on error goto eh startJournal = Sheets("Runsheet").Range("B5") endJournal = Sheets("Runsheet").Range("E5") If startJournal = 0 Or endJournal = 0 Then GoTo Error End If 'bunch of code Exit Function eh: MsgBox ("Error Statement") End Function 

看着你的代码,你可以把它写成

 Function getReports(startJournal as integer, endJournal as integer) as Boolean If startJournal = 0 Or endJournal = 0 Then msgbox "startJoural or endJournal should not be 0." exit function '** exiting will return default value False to the caller End If 'bunch of code getReports = True End Function 

在来电方

 if getReports(Sheets("Runsheet").Range("B5"), Sheets("Runsheet").Range("E5")) then call faxTheReport '** This function will be called only if getReports returns true. end if 

这里是我通常如何处理我的VBA代码中的错误。 这是从类中的代码中自动化一个Internet Explorer实例( IEvariables)的代码。 Log用于通知用户正在发生的事情。 variablesDebugUser是一个布尔值,当我是运行代码的时候,它被设置为true。

 Public Sub MyWorkSub() On Error GoTo e Nav "http://www.somesite.com" DoSomeSpecialWork Exit Sub e: If Err.Number = -2147012894 Then 'timeout error Err.Clear Log.Add "Timed Out... Retrying" MyWorkSub Exit Sub ElseIf Err.Number = -2147023170 Or Err.Number = 462 Or Err.Number = 442 Then RecoverIE Log.Add "Recovered from Internet Explorer Crash." Resume ElseIf Err.Number = 91 Then 'Page needs reloading Nav "http://www.somesite.com" Resume 'now with this error fixed, try command again End If If DebugUser Then Stop 'causes break so I can debug Resume 'go right to the error End If Err.Raise Err.Number End Sub