简体   繁体   English

出错后如何调用子程序?

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

I'm working on user-proofing a VBA app in Excel and I realized I'm constantly rewriting a lot of the same code to create specific error messages that are fed strings of info for the user to be able to tell me when they inevitably call me to say they're getting errors.我正在对 Excel 中的 VBA 应用程序进行用户校对,我意识到我一直在重写许多相同的代码来创建特定的错误消息,这些错误消息会被输入信息字符串,以便用户能够在他们不可避免的时候告诉我打电话给我说他们遇到了错误。

I want to create something like this to simply call on each error and pass the particulars:我想创建这样的东西来简单地调用每个错误并传递细节:

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

Then ideally I could use something like然后理想情况下我可以使用类似的东西

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

It seems like On Error only works with goto or resume;似乎 On Error 仅适用于 goto 或 resume; there are a bunch of modules that would need this in a lot of subs so writing basically this in a bunch of different GoTo blocks is annoying.有很多模块在很多子程序中都需要这个,所以基本上在一堆不同的 GoTo 块中写这个很烦人。 Is there a solution for me to use an error to call a sub like this?有没有解决方案让我使用错误来调用这样的子?

Encapsulate your error generators in a try function将错误生成器封装在 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

Then in your code you'd have然后在你的代码中你有

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