【问题标题】:Handling non integer in inputbox in VBA在 VBA 的输入框中处理非整数
【发布时间】:2015-03-26 19:57:48
【问题描述】:

我有一个名为“need”的变量,它被定义为一个整数。一个输入框出现并提示用户。如果他们输入一个整数,它会显示 Msgbox“得到你的号码”。如果我输入一个字符串,我会收到运行时错误“13”:类型不匹配。我想如果我只是使用 Else 语句,它会说再试一次。但它并没有这样做。我需要在 Else 语句中进行错误处理吗?如果是这样,这条线会是什么?

Sub gadgetmanuf()

Dim need As Integer
'Dim rawneed As Single
'Dim rawavailable As Single


    need = InputBox("How many gadgets are needed?", "Insert a number")

    If TypeName(need) = "Integer" Then
        MsgBox ("Got your number")
    Else
        MsgBox ("Try again")
    End If

End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    使用Application.InputBox 类型为1 会强制用户输入一个数字(为文本、范围等提供其自己的错误消息)。所以你只需要处理Cancel 选项,即

    下面的代码使用一个变体来处理这个问题,因为使用带有 IntegerLongCancel 给出 0 - 这可能是一个有效的条目。

    Sub TaylorWalker()
    redo:
    vStr = Application.InputBox("How many gadgets are needed?", "Enter a number", , , , , , Type:=1)
    If vStr = False Then GoTo redo
    End Sub
    

    更长的选择

    测试输入的变量是否大于0

    Sub EddieBetts()
    Dim StrPrompt As String
    Dim lngNum As Long
    
    StrPrompt = "How many gadgets are needed?"
    redo:
    lngNum = Application.InputBox(StrPrompt, "Enter an integer number (numbers will be rounded)", , , , , , Type:=1)
    If lngNum < 1 Then
        StrPrompt = "How many gadgets are needed - this must be a postive integer"
        GoTo redo
    End If
    
    MsgBox "User entered " & lngNum
    
    End Sub
    

    【讨论】:

      【解决方案2】:

      在您的示例中,“需要”是整数数据类型,因此它始终是整数。

      看看这个:

      Sub test()
        x = Range("A1").Value
        If Int(x) / x = 1 Then
          MsgBox "Value is an Integer"
        Else
          MsgBox "Value is not an Integer"
        End If
      End Sub
      

      或假设 A1 有数字,在任何其他单元格中放入公式:

      =IF(INT(A1)=A1,"True","False")
      

      【讨论】:

        猜你喜欢
        • 2013-12-24
        • 2022-09-30
        • 1970-01-01
        • 1970-01-01
        • 2015-04-26
        • 1970-01-01
        • 2010-11-19
        • 2014-08-20
        • 2021-08-13
        相关资源
        最近更新 更多