【问题标题】:How do I exit a do loop when I press the cancel button当我按下取消按钮时如何退出 do 循环
【发布时间】:2018-05-10 21:40:31
【问题描述】:
Sub msgbox_icons()
    Dim t As String, arg As Integer
    t = "Message Box Icons Demo"
    Do
        arg = InputBox(prompt:="Enter below one of the integers: (16, 32, 48 or 64):", Title:=t)
        If arg = 16 Then
            MsgBox arg & "<=> Critical Message Icon", vbCritical + vbOK, t
        ElseIf arg = 32 Then
            MsgBox arg & "<=> Warning Query Icon", vbQuestion + vbOK, t
        ElseIf arg = 48 Then
            MsgBox arg & "<=> Warning Message Icon", vbExclamation + vbOK, t
        ElseIf arg = 64 Then
            MsgBox arg & "<=> Information Message Icon", vbInformation + vbOK, t
        Else
            MsgBox arg & "<=> non-existent icon type", vbOKCancel, t
        End If
    Loop
End Sub

当我按下取消按钮时,它告诉我我遇到了 13 类错误。我想知道如何解决它。另外,如果我同时按下输入框和消息框的取消按钮,我将如何结束宏。谢谢。

【问题讨论】:

  • 错误出现在哪一行?

标签: excel vba macos inputbox do-loops


【解决方案1】:

由于取消按钮的返回值是一个空字符串,所以arg变量必须是一个字符串,然后询问它是否是数字你可以判断是否按下了取消按钮,使用“Exit Do”退出循环,你的代码可能是这样的:

Sub msgbox_icons()
    Dim arg, t As String

    t = "Message Box Icons Demo"
    Do
        arg = InputBox(Prompt:="Enter below one of the integers: (16, 32, 48 or 64):", Title:=t)
        If Not IsNumeric(arg) Then
            Exit Do
        ElseIf arg = 16 Then
            MsgBox(arg & "<=> Critical Message Icon", vbCritical + vbOK, t)
        ElseIf arg = 32 Then
            MsgBox(arg & "<=> Warning Query Icon", vbQuestion + vbOK, t)
        ElseIf arg = 48 Then
            MsgBox(arg & "<=> Warning Message Icon", vbExclamation + vbOK, t)
        ElseIf arg = 64 Then
            MsgBox(arg & "<=> Information Message Icon", vbInformation + vbOK, t)
        Else
            MsgBox(arg & "<=> non-existent icon type", vbOKCancel, t)
        End If
    Loop
End Sub

【讨论】:

  • 注意:目前arg 是一个变体。 VBA 将变量默认为变量,除非 每个 变量被显式 分配了特定类型。
  • @mistella 在这个答案中是故意和必要的,以避免按下 Esc 时出现错误
  • @misael 您需要删除 MsgBox 参数周围的 ()
  • @chrisneilsen 我只是想明确说明/澄清这一点,因为我已经看到人们使用这种格式的多个实例,期望 arg 被定义为一个字符串,或者使用类似 Dim t, c as Integer 和期望 t 结果是一个整数。 (另外,从@Misael 所说的the arg variable must be a string 这意味着(错误)理解arg 在代码中是如何定义的)
  • @mistella 重读我同意的帖子,OP 可能打算将 arg 用作字符串。
猜你喜欢
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-22
  • 2020-05-21
  • 1970-01-01
  • 2015-07-19
相关资源
最近更新 更多