不明白为什么我会遇到编译错误

时间:2018-11-16 21:20:23

标签: excel vba excel-vba

我遇到了一个编译错误:否则,如果没有If并且我不确定为什么。

Dim product As String

    Do Until product = "P" Or product = "p"
    product = Left(InputBox("Please enter product number", "Product please", "Enter product number here"), 1)
        If product = "P" Or product = "p" Then MsgBox "Thank you"
        ElseIf product = "Enter product number here" Then Exit Sub
        Else: MsgBox "Please enter a valid product number"
        End If
    Loop

2 个答案:

答案 0 :(得分:2)

由于您的If语句要复杂一些,所以只需“如果此条件为真,就做一件事”,则应将条件与操作分开放在自己的行中:

Dim product As String

Do Until product = "P" Or product = "p"
    product = Left(InputBox("Please enter product number", "Product please", "Enter product number here"), 1)

    If product = "P" Or product = "p" Then 
         MsgBox "Thank you"
    ElseIf product = "Enter product number here" Then 
         Exit Sub
    Else
         MsgBox "Please enter a valid product number"
    End If
Loop

正如我在评论中指出的那样,如果您运行此代码,则ElseIF条件将永远不会发生,并且将陷入无限循环。

答案 1 :(得分:0)

考虑一下逻辑流程-将IF放在同一行后第一个MsgBox之后会发生什么。使用F8进入下面的代码以找出答案。干杯!

Sub test()

    Dim product As String

    Do Until product = "P" Or product = "p"
        product = Left(InputBox("Please enter product number", "Product please", "Enter product number here"), 1)
        If product = "P" Or product = "p" Then
            MsgBox "Thank you"
            ElseIf product = "Enter product number here" Then Exit Sub
            Else: MsgBox "Please enter a valid product number"
        End If
    Loop

End Sub