有时你给客户一个exe,但是发现有地方出错,又不可能放源码,可以采用这个方法看到出错的地方。
新建From1(窗体),代码:
Private Sub Form_Load()
On Error GoTo hErr
Dim a As Long, b As Long
a = 100
b = a \ 0
Exit Sub
hErr:
MsgBox "Error Line: " & Erl & vbCrLf & "Error " & Err.Number & " (" & Err.Description & ") ", vbCritical, "Error"
Exit Sub
End Sub
Private Sub s_1()
Dim x As Long
x = 1
End Sub
插件MZTools的一个功能【Add Line Numbers】给当前过程增加行号,当然【Remove Line Numbers】是移除行号。网上有的VB代码网页中每行前面有行号,拷贝出来不好看,用这个功能可以批量去掉全部行号。
当我鼠标点击在Form_Load的空间时使用【Add Line Numbers】,代码就变成了:
Private Sub Form_Load()
10 On Error GoTo hErr
Dim a As Long, b As Long
20 a = 100
30 b = a \ 0
40 Exit Sub
hErr:
50 MsgBox "Error Line: " & Erl & vbCrLf & "Error " & Err.Number & " (" & Err.Description & ") ", vbCritical, "Error"
60 Exit Sub
End Sub
Private Sub s_1()
Dim x As Long
x = 1
End Sub
直接在IDE运行或生成exe(点击错误后可以Ctrl+C拷贝错误,哈哈真方便)可以看到:
---------------------------
Error
---------------------------
Error Line: 30
Error 11 (除数为零)
---------------------------
确定
---------------------------
然后找源代码看30行,发现是除以0导致。
当然我们也有可以用 Err.Raise (11) 伪造一个错误11。
Private Sub Form_Load()
10 On Error GoTo hErr
Dim a As Long, b As Long
20 a = 100
30 Err.Raise (11)
'b = a \ 0
40 Exit Sub
hErr:
50 MsgBox "Error Line: " & Erl & vbCrLf & "Error " & Err.Number & " (" & Err.Description & ") ", vbCritical, "Error"
60 Exit Sub
End Sub
效果一样。