VBA Excel,输入框不匹配为整数

Osk*_*ger 9 excel vba excel-vba

我的代码

Dim a As Integer
a = InputBox("Enter the number", "Program", "", 7000, 6000)
If a = Empty Then
    ' do code...
Else
    MsgBox "Enter the number."
End If
Run Code Online (Sandbox Code Playgroud)

如果我留下一个空字段,Excel将返回Type Mismatch错误.我想显示一条消息.

Oll*_*ren 15

既然aInteger,它不能包含String或者是Empty.使用a Variant然后检查以查看返回的内容:

Dim a As Variant
Dim b As Integer

a = InputBox("Enter the number", "Program", "", 7000, 6000)

If Not IsNumeric(a) Then
    'a is not a number
Else
    'a is a number and can be converted to Integer
    b = CInt(a)
End If
Run Code Online (Sandbox Code Playgroud)


And*_*eev 5

a定义为Integer.Integer不能为空.使用Variant而不是Integer:

Dim a As Variant
a = InputBox("Enter the number", "Program", "", 7000, 6000)
If a = Empty Then
    ' do code...
Else
    MsgBox "Enter the number."
End If
Run Code Online (Sandbox Code Playgroud)

  • @OskarStrasburger,这是您的初始问题中未包含的新信息. (3认同)
  • 第一个正确答案的+1 - 尽管你确实想要`If IsEmpty(a)Then` (2认同)