我正在尝试确保我的错误捕获工作正常但不确定我理解处理在另一个模块中发现的错误的正确过程。
如果我在module1
Sub test()
. . . . 'macro code Part1
SAtext = SAdata(SApage, "A")
. . . . . 'macro code part2
my5Error:
ASSoffice = Empty
prv1 = Empty
TNT = Empty
End sub
我希望宏代码part1运行并调用SAdata函数。当函数运行时,我希望它运行函数代码part1,然后检查是否会发生err.number = 5。如果没有,则重置错误处理,但如果确实如此,我希望它跳过'功能代码part2'部分并在myBlank上运行代码:这部分似乎工作正常。
Function SAdata(SApage, "A")
. . . . Function code part1
On Error Resume Next
myresponse = Mid(xmlHTTP.responseText, InStr(1, xmlHTTP.responseText, "Ref No.", vbTextCompare), Len(xmlHTTP.responseText))
If Err.Number = 5 Then GoTo myBlank
On Error GoTo 0
. . . . . function code part2
myBlank:
Set xmlHTTP = Nothing
Set oDoc = Nothing
Set objData = Nothing
On Error GoTo 0
End Function
在完成函数的错误处理后,如何识别函数中发生错误并跳过“宏代码part2”部分?
答案 0 :(得分:0)
如果使用全局
,这样的话Option Explicit
Public error5 As Boolean
Sub test()
'. . . . 'macro code Part1
SAtext = SAdata(SApage, "A")
If error5 Then
'. . . . . 'macro code part2
End If
'....
End Sub
Public Function SAdata(SApage , "A" )
'. . . . Function code part1
On Error Resume Next
myresponse = Mid(xmlHTTP.responseText, InStr(1, xmlHTTP.responseText, "Ref No.", vbTextCompare), Len(xmlHTTP.responseText))
If Err.Number = 5 Then GoTo myBlank
On Error GoTo 0
'. . . . . function code part2
Exit Function
myBlank:
error5 = True
Set xmlHTTP = Nothing
Set oDoc = Nothing
Set objData = Nothing
On Error GoTo 0
End Sub
这是一个粗略且准备好的测试用例
Option Explicit
Public error5 As Boolean
Sub test()
'. . . . 'macro code Part1
Dim SAPage As Variant
Dim SAtext As String
SAPage = 1
SAtext = SAdata(SAPage, "A")
If error5 Then
'. . . . . 'macro code part2
Debug.Print "The was a runtime error: " & error5
Else
Debug.Print "No show"
End If
'....
End Sub
Public Function SAdata(ByVal SAPage As Variant, Optional ByVal myString As String = "A") As String
Dim myresponse As String
Dim xmlHTTP As Object
Dim oDoc As Object
Dim objData As Object
'. . . . Function code part1
On Error Resume Next
myresponse = Mid(vbNullString, Len(vbNullString) - 1)
If Err.Number = 5 Then GoTo myBlank
On Error GoTo 0
'. . . . . function code part2
Exit Function
myBlank:
error5 = True
Set xmlHTTP = Nothing
Set oDoc = Nothing
Set objData = Nothing
On Error GoTo 0
End Function
答案 1 :(得分:0)
另一种方法是重新抛出错误而不是使用全局标志。然后在调用方法中添加错误处理。在以下代码中,我添加了必要的代码,包括Exit Sub
:
Sub test()
'macro code Part1
On Error GoTo my5Error
SAtext = SAdata(SApage, "A")
On Error GoTo 0
'macro code part2
Exit Sub
my5Error:
ASSoffice = Empty
prv1 = Empty
TNT = Empty
On Error GoTo 0
End Sub
在以下代码中,请勿忘记包含Exit Function
语句,然后在最后添加Err.Raise
。
Function SAdata(SApage, SALetter)
'Function code part1
On Error Resume Next
myresponse = Mid(xmlHTTP.responseText, InStr(1, xmlHTTP.responseText, "Ref No.", vbTextCompare), Len(xmlHTTP.responseText))
If Err.Number = 5 Then GoTo myBlank
On Error GoTo 0
'function code part2
Exit Function
myBlank:
Set xmlHTTP = Nothing
Set oDoc = Nothing
Set objData = Nothing
On Error GoTo 0
Err.Raise vbObjectError + 513, "SAdata", "My error"
End Function