3

下面的代码看不懂,求大神帮忙。

它不断返回针对变量 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
4

3 回答 3

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
于 2012-12-14T07:43:59.360 回答
1

我认为这是一个逻辑缺陷。改变

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

进入

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

于 2012-12-14T09:46:11.863 回答
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

采用

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

编辑:

当您对 Do 循环使用正确的语法时,您的代码会因为您构造 While 条件的方式而进入无限循环。例如,如果 inputBox 检索到“B”,则它是“<>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
于 2012-12-14T09:05:10.337 回答