我正在遍历行,并使用不同的函数查找每行(名称)的第一列来查找他的标记。
对于每个“名称”,在不同的表中都有一个特定的条目(“标记”),也可以为空白或“-”
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“类型不匹配”
我什至尝试在循环内添加错误语句 VBA 通常应该在调用函数(即“main”)中搜索错误处理,但它没有这样做
最佳答案
经过尝试和测试
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,抱歉,我没有看到您已经接受了答案。
跟进
block 引用> block 引用>actually i dont want to print any error message instead straightaway skip to the next iteration – Kartik Anand 14 secs ago
在这种情况下,您正在错误的部分处理错误;)
试试这个
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
关于excel - 当调用函数生成错误时,VBA 错误处理不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9581552/