繁体   English   中英

出错后如何调用子程序?

[英]How can I call a subroutine after an error?

我正在对 Excel 中的 VBA 应用程序进行用户校对,我意识到我一直在重写许多相同的代码来创建特定的错误消息,这些错误消息会被输入信息字符串,以便用户能够在他们不可避免的时候告诉我打电话给我说他们遇到了错误。

我想创建这样的东西来简单地调用每个错误并传递细节:

Sub GenericError(ErrNum As Long, ErrDesc As String, sequence As String, errtype As String)
'In case of error, returns actual error code and calls for abort; if no abort then can debug
Dim msgstrng As String
msgstring = sequence & " error " & errtype _
    & vbLrCf & "Error code " & ErrNum & " - " & ErrDesc
MsgBox msgstring, , sequence & " Error!"
cont = Abort_Check()
On Error GoTo 0
End Sub

然后理想情况下我可以使用类似的东西

On Error Call GenericError(Err.Number, Err.Description, "Startup Sequence", "File Not Found")
'code that opens a file....
On Error goto 0

似乎 On Error 仅适用于 goto 或 resume; 有很多模块在很多子程序中都需要这个,所以基本上在一堆不同的 GoTo 块中写这个很烦人。 有没有解决方案让我使用错误来调用这样的子?

将错误生成器封装在 try 函数中

Public Function TryDoThisThing( byval ipInput1 as variant, byval input2 as variant,byref opReturnValue as variant, byref opErrorNumber as long, byref opErrorDescription as String) as boolean

   On Error Resume Next
   opReturnValue = DoThistThing(ipInput1, ipInput2)
   TryDoThisThing = err.number = 0
   opErrorNumber = err.number
   opErrorDewscription = Err.description
   Err.Clear

Exit Function

然后在你的代码中你有

If not TryDoThisThing(val1, val2, myResult, myErrNo,myErrDesc) then

    GenericError myErrNo, myErrDesc, sequence , errtype
    <any other corrective actions>
end if

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM