VBA中的错误GOTO语句
我用这段代码使用Ctrl+F命令在excel工作表中查找特定值,但当代码找不到任何内容时,我希望它抛出一条消息VBA中的错误GOTO语句,vba,excel,Vba,Excel,我用这段代码使用Ctrl+F命令在excel工作表中查找特定值,但当代码找不到任何内容时,我希望它抛出一条消息 sub test() f=5 do until cells(f,1).value="" On Error goto hello Cells.Find(what:=refnumber, After:=ActiveCell, LookIn:=xlFormulas, _ lookat:=xlP
sub test()
f=5
do until cells(f,1).value=""
On Error goto hello
Cells.Find(what:=refnumber, After:=ActiveCell, LookIn:=xlFormulas, _
lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
f=f+1
hello: Msgbox"There is an error"
loop
endsub
问题是,即使没有发现错误,消息仍会显示。我希望消息框仅在出现错误时显示。在这种情况下,您应该使用
退出子项
或退出功能
,并让您的hello
标签显示代码的最后一部分。见示例:
Sub test()
f = 5
On Error GoTo message
check:
Do Until Cells(f, 1).Value = ""
Cells.Find(what:=refnumber, After:=ActiveCell, LookIn:=xlFormulas, _
lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
Loop
Exit Sub
message:
MsgBox "There is an error"
f = f + 1
GoTo check
End Sub
在
hello:Msgbox“有错误”
之前,您需要一行exit sub
(或者exit function
,如果这是函数的一部分而不是sub),否则它下面的代码将始终被执行。请参阅本文作为参考-
代码示例-
on error goto bad
call foo
exit sub
bad:
msgbox "bad"
'clean up code here
exit sub
public sub foo
msgbox 1/0 'could also trigger the error handling code by doing err.raise, to use user defined errors
end sub
更新:
要修复循环,您应该将错误处理代码移到循环之外,但仍要将exit子项
保留在它之前,以防止它被执行
sub test()
f=5
do until cells(f,1).value=""
On Error goto hello
Cells.Find(what:=refnumber, After:=ActiveCell, LookIn:=xlFormulas, _
lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
loop
exit sub
hello:
Msgbox"There is an error"
endsub
使用
Err.Number
,例如:如果Err.Number为0,则Msgbox“存在错误”
确定如果我有多个这样的条件,VB如何知道哪个Err.Number属于哪个条件Err
对象包含有关运行时错误的信息。出现错误时,将填充Err
对象的属性。因此,Err
对象不属于它仅通知是否发生错误的任何条件。请参见Err.Clear
。exit sub和end sub之间的区别是什么?我不希望代码在出错后结束,我希望代码继续,没有任何内容,exit
是停止当前进程的关键字。因此,对于退出函数
使用退出函数
,对于退出子函数
,使用退出子函数
我已经更新了问题,我不想退出do-until循环。好吧,假设代码在第一次迭代中发现错误并打印了消息,现在,它会返回到循环并继续执行其余语句,直到“DO-until”语句得到满足吗?我已经更新了这个问题,我不想退出DO-until循环我知道在找到错误时它会出来,但我希望它返回到循环中。它是possible@Anarach您将需要一个单独的goto语句(在错误处理代码中),它将您带回循环(当然之前是条件测试)。如何做到这一点?在“message”之后再写一条goto语句返回循环?这样行吗?它会继续吗?这样做是一种混乱的做法。不过,我建议你重新思考你正在设计的东西,因为你似乎认为会经常出现错误。