【问题标题】:On error GOTO statement in VBA关于 VBA 中的错误 GOTO 语句
【发布时间】:2015-08-13 11:01:30
【问题描述】:

我有这段代码可以使用 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

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

【问题讨论】:

  • 使用Err.Number,例如:If Err.Number <> 0 then Msgbox"There is an error"
  • 好的,如果我有多个这样的条件,VB如何知道哪个err.number属于哪个条件
  • Err 对象包含有关运行时错误的信息。发生错误时将填充Err 对象的属性。所以Err 对象不属于它只是通知是否发生错误的任何条件。参见Err.Clear

标签: vba excel


【解决方案1】:

对于这种情况,您应该使用 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

【讨论】:

  • exit sub和end sub有什么区别?
  • 我不希望代码在错误后结束,我希望它继续,
  • 没什么,Exit 是停止当前进程的关键字。所以,退出Funciton使用Exit Function,退出Sub,使用Exit Sub
  • 我已经更新了问题,我不想退出循环。
  • 好吧,假设代码在第一次迭代中发现错误并打印了消息,现在它会返回循环并继续执行其余语句,直到“DO until”陈述是否满意?
【解决方案2】:

您需要在hello: Msgbox"There is an error" 之前添加exit sub(或exit function,如果这是函数的一部分而不是子代码)行,否则将始终执行它下面的代码。请参阅这篇文章作为参考-

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

【讨论】:

  • 我已经更新了问题,我不想退出循环
  • 我知道在发现错误时它会出现,但我希望它回到循环中。有没有可能
  • @Anarach 你需要一个单独的 goto 语句(在错误处理代码中),这会让你回到循环中(当然是之前的条件测试)。
  • 怎么做?在“消息”之后写另一个 goto 语句以返回循环?它会那样工作吗?会继续吗
  • IMO 这样做是一种混乱的做法,但我建议重新考虑您正在设计的任何内容,因为您似乎希望经常出现错误。
猜你喜欢
  • 2012-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多