2017-09-13 176 views
0

嘿,夥計們我要寫我的第一個基本步驟在VBA中,我遇到了以下問題。VBA InputBox運行錯誤(錯誤的變量類型)重新運行InputBox

Test1: 
qm = InputBox("Wie viele Quadrat Meter hat die Wohnung?" & vbLf & "Bitte geben sie die QM Zahl an.", Angabe) 
If IsError(qm) Then GoTo Test1 

qm被定義爲Integer,= O,和下面有一個Select Case mutilple替代從1-600變化qm爲數字。

當InputBox運行時,我輸入一個像「嗨夥計」一樣的Word,Excel給了我錯誤13(運行時錯誤13':類型錯配)。

我的目標是在崩潰時重新運行InputBox,併爲用戶提供一個給Number輸入正確輸入的新機會。 (就像它崩潰,你會得到一個msgbox它說「對不起你的輸入不可用,請重試」,它會跳回msg框)

我試圖找到一個適合的解釋堆棧溢出和谷歌搜索但它卻無法找到與解決方案相同的問題。

如果你能幫我解決方案或鏈接我一個合適的現有解釋我會非常感激。

+0

您可以使用** ** VBA的'Application.InputBox'版本,請參閱我的回答下面 –

回答

2

這就是爲什麼在VBA你可以用一個第四個參數Type使用Application.InputBox。如果您使用Type:=1那麼只允許數字值。

代碼

Dim qm As Integer 

qm = Application.InputBox("Wie viele Quadrat Meter hat die Wohnung?" _ 
      & vbLf & "Bitte geben sie die QM Zahl an.", "Angabe", Type:=1) 
+0

非常感謝編輯我的問題,使它更具可讀性。 Allpication.Inputbox工作得很好,我會嘗試將您的編輯作爲未來發布和答案的示例。 – Lutscha

2

嘗試像下面

Sub Demo() 
    Dim qm As String 
    qm = 0 
Test1: 
    qm = InputBox("Enter value") 
    If Not IsNumeric(qm) Then GoTo Test1 
End Sub 

聲明qmString,並檢查其是否數字或沒有。然後,您必須使用CInt()String轉換爲Integer

+0

謝謝。 IsNumeric()解決方案是爲我的任務提供的技巧,但我很高興你向我展示瞭如何正確使用它。 – Lutscha

1

有多種方法可以解決這個問題。我建議定義一個變量variant(可以保存任何數據類型),並檢查它是否是數字:

dim answer as variant, qm as integer 
do while true 
    answer = InputBox(...) 
    if isNumeric(answer) then 
     qm = cInt(answer) 
     exit do 
    endif 
loop 
+0

對我來說,這是一個聰明的解決方案。非常感謝。 – Lutscha

1

您可以設置一個事件每次改變時間來驗證文本框的內容去。我檢查了這是一個數字,但你可以驗證你需要的任何其他條件。

Private Sub TextBox1_Change() 
    validator = IsNumeric(TextBox1.Value) 
    If validator = False Then 
    MsgBox "WARNING! You must enter a number!" 
    TextBox1.BackColor = &HFF8& 
    End If 
End Sub