我正在遍历行,并使用不同的函数查找每行(名称)的第一列以查找其标记。
对于每个“名称”,在不同的表(“标记”)中有一个特定的条目,也可以是空白或“ - ”
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”,但它没有这样做
答案 0 :(得分:2)
已经过测试
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
答案 1 :(得分:0)
在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