我有这段代码使用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
问题是,即使没有发现错误,消息仍然会显示出来。我希望仅在出现错误时显示消息框。
答案 0 :(得分:4)
对于这种情况,您应该使用Exit Sub
或Exit 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
答案 1 :(得分:4)
exit sub
之前需要exit function
(或hello: Msgbox"There is an error"
如果这是函数的一部分而不是子代码),或者下面的代码将始终执行。请参阅此文章作为参考 -
How to stop VBA macro automatically?
代码示例 -
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
,以防止它被执行。
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