gpt4 book ai didi

excel - 调用函数生成错误时,VBA 错误处理不起作用

转载 作者:行者123 更新时间:2023-12-04 20:19:55 25 4
gpt4 key购买 nike

我正在遍历行,并使用不同的函数查找每行(名称)的第一列以查找他的标记。

对于每个“名称”,在不同的表中都有一个特定的条目(“标记”),也可以是空白或“-”

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,对不起,我没有看到你已经接受了答案。

跟进

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com