VBA 中的错误 GOTO 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31986386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
On error GOTO statement in VBA
提问by Anarach
I have this code to find a particular value in an excel sheet using the Ctrl+F command , but when the code does not find anything i want it to throw a message.
我有这段代码可以使用 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:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
f=f+1
hello: Msgbox"There is an error"
loop
endsub
The problem is that even if no error is found the message is still getting shown. I want the message box to be shown only when there is an error.
问题是即使没有发现错误,消息仍然会显示。我希望仅在出现错误时才显示消息框。
回答by R.Katnaan
For that case you should use Exit Subor Exit Functionand let your hellolabel to the last part of code. See sample:
对于这种情况,您应该使用Exit SuborExit Function并将您的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
回答by iliketocode
You need an exit sub(or exit functionif this is part of a function instead of a sub) line of code before hello: Msgbox"There is an error", or else the code below it will always be executed. See this post as a reference-
您需要在 之前exit sub(或者exit function如果这是函数的一部分而不是子)代码行hello: Msgbox"There is an error",否则它下面的代码将始终被执行。请参阅此帖子作为参考-
How to stop VBA macro automatically?
Code example-
代码示例-
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
Update:
更新:
To fix your loop, you should move the error handling code outsideof the loop, but still keep the exit subbefore it, to prevent it from being executed regardless.
要修复您的循环,您应该将错误处理代码移到循环之外,但仍保留它exit sub之前的代码,以防止它无论如何都被执行。
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

