错误VBA中的GOTO语句

我有这个代码,使用Ctrl + F命令在Excel工作表中find一个特定的值,但是当代码没有find任何我想要的信息时。

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 

问题是,即使没有发现错误消息仍然显示。 我希望消息框仅在出现错误时才显示。

在这种情况下,您应该使用Exit SubExit 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 

你需要在hello: Msgbox"There is an error"之前hello: Msgbox"There is an error"一个exit sub (或exit function如果这是exit function一部分而不是子行) hello: Msgbox"There is an error" ,否则它下面的代码将一直执行。 看到这个职位作为参考 –

如何自动停止VBAmacros?

代码示例 –

 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 

更新:

为了修复你的循环,你应该把error handling代码移到循环之外 ,但是仍然保留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