2012-12-14 101 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

相关问题