2012-12-14 140 views
3

我不明白下面的代碼,請幫助。類型不匹配VBA錯誤聲明爲字符串變量

它一直對變量b返回一個類型不匹配錯誤。

Dim a As Integer 
Dim b As String 

a = InputBox("Input the number of items", "Total Number of Items.") 
b = InputBox("Which Block?", "Total Number of Items.") 

Do While b <> "a" Or "A" Or "B" Or "b" 
     MsgBox ("Invalid Block. Try again, Input A or B") 
     b = InputBox("Which Block?", "SELECT BLOCK.") 
Loop 
    If b = "a" Or "A" Then 
     Me.ComboBox1.List = Worksheets("Sheet1").Range("a3:a39").Value 
    Else 
     Me.ComboBox2.List = Worksheets("Sheet2").Range("a3:a35").Value 
    End If 
+0

@JüriRuut,我已經試過代碼 待辦事項而B <> 「A」 或B'> 「A」 或B'> 「B」或b <>「b」 ,但即使我已經輸入A或B,循環也不會停止。它始終顯示msgbox。我不得不使用任務管理器來停止它... –

+1

沒有看得太徹底的內容:-(而不是任務管理器,Ctrl-Break可以用來停止執行代碼 –

+0

我認爲一個簡單的解決方案是'b = CStr(InputBox(「Which Block?」,「Total Number of Items。」))'還有line:'b = CStr(InputBox(「Which Block?」,「SELECT BLOCK。」))' – Larry

回答

1

我認爲這是一個邏輯缺陷。更改

Do While UCase$(b) <> "A" or UCase$(b) <> "B"

INTO

Do While UCase$(b) <> "A" AND UCase$(b) <> "B"

+0

我也試過它,並且循環不會停止...繼續返回輸入框... –

+0

這已經是我的初始代碼正確,OP沒有像我發佈的那樣使用它。 – brettdj

+0

@brettdj嗨對不起,我沒有通過所有的代碼...只是標題之一...而我沒有複製你的答案..你可以從聊天中看到的問題,我經歷了調試階段,讓我自己的回答。 – Larry

5

您可以使用Application.InputBox強制文本輸入a和和數字輸入b

使用UCASE$縮短您的測試

Dim a As Long 
Dim b As String 

a = Application.InputBox("Input the number of items", "Total Number of Items.", , , , , , 1) 
b = Application.InputBox("Which Block?", "Total Number of Items.", , , , , 2) 

Do While UCase$(b) <> "A" And UCase$(b) <> "B" 
b = Application.InputBox("Which Block?", "Invalid Entry - Total Number of Items.", , , , , 2) 
Loop 
+0

類型不匹配,當我鍵入A時? –

+0

+ 1的額外參數... –

+0

你是否在輸入* A *時提示輸入'b'? – brettdj

0

問題是你如何測試的「B」變量。

錯誤

Do While b <> "a" Or "A" Or "B" Or "b" 

Do While b <> "a" Or b <> "A" Or b <> "B" Or b <> "b" 

這同樣適用於if子句

If b = "a" Or "A" Then 

使用

Istead
If b = "a" Or b = "A" Then 

編輯:

當您使用DO循環正確的語法,你的代碼進入一個無限循環,因爲你是如何構建的雖然條件。 例如,如果inputBox檢索到「B」,則它是「s」<> b「或」<> a「或...因此它將再次進入循環。無論用戶輸入什麼,它總是會與其他任何條件不同。

編輯2:

請試試這個。它檢索到相同的錯誤?

Sub TryThis() 
    Dim a As Integer 
    Dim b As String 

    a = InputBox("Input the number of items", "Total Number of Items.") 
    b = InputBox("Which Block?", "Total Number of Items.") 

    Do While b <> "a" And b <> "A" And b <> "B" And b <> "b" 
      MsgBox ("Invalid Block. Try again, Input A or B") 
      b = InputBox("Which Block?", "SELECT BLOCK.") 
    Loop 

    Debug.Print "InputBox b Correctly filled" 

    If b = "a" Or b = "A" Then 
     Debug.Print "User Input A" 
    Else 
     Debug.Print "User Input: " & b 
    End If 
End Sub 
+0

我看到他在OP自己的問題評論中發佈了「RIGHT」。我認爲他改變了? – Larry

+0

我已經試過這已經: 待辦事項而B <> 「A」 或B'> 「A」 或B'> 「B」 或B'> 「B」 但還是類型不匹配.. –

+0

我錯過那個評論。感謝您指出我們的@Larry。我編輯了答案來解決這個問題。 – CaBieberach

相關問題