2013-02-11 28 views
8

我的代碼VBA Excel中,不匹配輸入框爲整數

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 

如果我離開的空場時,Excel返回Type Mismatch錯誤。我想顯示一條消息。

回答

11

由於aInteger,它不能包含String或者是Empty。使用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 
4

你有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 
+1

+1的第一個正確的答案 - 儘管你想'如果爲IsEmpty(一)Then' – brettdj 2013-02-11 10:12:56

+0

我+1佈雷特) – 2013-02-11 10:14:23

+0

@brettdj爲什麼不你發佈自己的答案嗎? :) – 2013-02-11 10:15:59