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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14809830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:56:23  来源:igfitidea点击:

VBA Excel, mismatch for inputbox as integer

excelvbaexcel-vba

提问by Oskar Strasburger

My code

我的代码

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

If I leave an empty field , Excel returns a Type Mismatcherror. I would like to display a message.

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

回答by Olle Sj?gren

Since ais an Integer, it cannot contain a Stringor be Empty. Use a Variantand then check to see what has been returned:

由于a是 an Integer,它不能包含 aString或 be Empty。使用 aVariant然后检查返回的内容:

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

回答by Andrey Gordeev

You have adefined as Integer. Integercannot be empty. Use Variantinstead of Integer:

您已a定义为IntegerInteger不能为空。使用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