2016-11-18 44 views
0

我試圖獲取用戶手動輸入一個整數的值,我必須考慮到用戶可能不輸入整數的事實。這就是爲什麼我試圖捕捉類型不匹配錯誤。但是,當我輸入一個整數值時,我仍然遇到類型不匹配錯誤。無法將數據從InputBox解析爲整數(Visual Basic for Excel)

這是導致此錯誤的一段代碼。

Dim number As Integer 
On Error GoTo error 
    number = InputBox("Enter an integer:") 
error: 
    MsgBox ("Input error. Make sure you enter an integer value.") 
    Exit Sub 
+1

前請'錯誤增加到'退出sub':' –

+1

您沒有任何機制有跳過錯誤消息,所以它總是會出現。 – Rory

+0

再一個建議 - 儘量避免使用自己的名字時的保留字或保留字。因此,而不是'錯誤'標籤,你可以使用相當常見的'ErrorHandler' –

回答

2

Application.InputBox Method允許您指定返回的數據類型。

MSDN Application.InputBox Method (Excel)

enter image description here

Sub Example1() 
    Dim number As Integer 
    number = Application.InputBox(Prompt:="Enter an integer:", Type:=1) 

End Sub 

因爲Application.InputBox與1型參數,如果用戶取消將返回0,我寧願使用標準InputBox。使用它的方法是讓一個單獨的變量捕獲值並測試返回值是否符合您的標準。這樣可以避免任何錯誤。

Sub Example2() 
    Dim number As Integer 
    Dim result As String 
    result = InputBox("Enter an integer:") 
    If result = "" Then 
     MsgBox "Good Bye", vbInformation, "Action Cancelled" 
     Exit Sub 
    ElseIf IsNumeric(result) Then 
     If CDbl(result) > CInt(result) Then 
      MsgBox "You entered a Decimal" & vbCrLf & "Try Again", vbInformation, "Intergers Only" 
     Else 
      number = result 
     End If 
    Else 
     MsgBox "Intergers Only" & vbCrLf & "Try Again", vbInformation, "Intergers Only" 
    End If 

End Sub 
+0

謝謝。有效。 –

0

這裏有一種方法:

Dim number    As Integer 
On Error Resume Next 
number = InputBox("Enter an integer:") 
If Err.number <> 0 Then 
    MsgBox ("Input error. Make sure you enter an integer value.") 
    Exit Sub 
End If 
On Error GoTo 0 

但請注意,這將接受非整數項;目前還不清楚這是否是一個問題。

+0

謝謝。這工作雖然我不得不修改它,所以它只存儲整數值。 –