调用函数时VBAerror handling不起作用产生错误
我遍历行,并查找每行(名称)的第一列使用不同的functionfind他的标记。
对于每个“名称”,在不同的表(“标记”)中都有一个特定的条目,这些条目也可以是空的或“ – ”
Sub main() On error goto errorhandler Dim name as string Dim marks as double Dim source as range Dim runs as integer runs = 1 Set source = Sheets("input").Range("$A$2") i=1 Do until source.offset(i,0) = "" 'iterate through rows name = source.offset(i,0) marks = find(name) do until runs * marks > 100 runs = runs + 1 'since marks is not defined;runs overflows Loop 'a lot of code which relies on marks errorhandler: i = i + 1 Loop End Sub Function find(name as string) as double find = application.vlookup(name,Sheets("values").Range("$A$2,$C$5"),2,0) End function
现在正如我所说,该表第2列中的值也可以是空白或“ – ”,从而导致错误运行时错误13“types不匹配”
我甚至尝试在循环内部放置错误语句VBA通常应该在调用函数中searcherror handling,即“主”,但它不这样做
Err.Clear
后添加一个errorhandler:
此外,请参阅Err.Clear
上的Excel帮助,其中包含On Error Resume Next
再加上If Err.Number <> 0 Then
这将产生更清晰的代码
就像是
Sub main() On Error Resume Next Dim name As String Dim marks As Double Dim source As Range Set source = Sheets("input").Range("$A$2") i = 1 Do Until source.Offset(i, 0) = "" 'iterate through rows name = source.Offset(i, 0) marks = Find(name) If Err.Number <> 0 Then Err.Clear Else ' Your other code for non-error case here End If i = i + 1 Loop End Sub
尝试和testing
Sub main() On Error GoTo errorhandler Dim name As String Dim marks As Double Dim source As Range Set source = Sheets("input").Range("$A$2") i = 1 Do Until source.Offset(i, 0) = "" 'iterate through rows name = source.Offset(i, 0) marks = find(name) Debug.Print marks i = i + 1 Loop Exit Sub errorhandler: MsgBox Err.Description End Sub Function find(name As String) As Double find = Application.WorksheetFunction.VLookup(name, Sheets("values").Range("$A$2:$C$5"), 2, False) End Function
编辑:Kartik,对不起,我没有看到你已经接受了答案。
跟进
实际上我不想打印任何错误信息,而是直接跳到下一个迭代 – Kartik Anand 14秒前
在这种情况下,你正在处理错误的部分错误;)
尝试这个
Sub main() Dim name As String Dim marks As Double Dim source As Range Set source = Sheets("input").Range("$A$2") i = 1 Do Until source.Offset(i, 0) = "" 'iterate through rows name = source.Offset(i, 0) marks = find(name) Debug.Print marks i = i + 1 Loop End Sub Function find(name As String) As Double On Error GoTo earlyexit find = Application.WorksheetFunction.VLookup(name, Sheets("values").Range("$A$2:$C$5"), 2, False) Exit Function earlyexit: find = 0 End Function