做while循环不停止

时间:2018-11-20 16:30:00

标签: excel vba excel-vba

我有以下do循环,当我想要时,它不会退出循环。我只是想让循环在输入P或p后结束,或者如果没有输入任何一个则继续执行。我想念什么?谢谢!

Private Sub btnDoWhile_Click()

    Dim product2 As String

    With wsLoops

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

    End With

End Sub

2 个答案:

答案 0 :(得分:2)

您可以通过这种方式(以及其他方式)简化逻辑。

Private Sub btnDoWhile_Click()

    Dim product2 As String

    Do

        product2 = Left(InputBox("Please enter product number", "Product please", "Enter product number here"), 1)

        If LCase$(product2) = "p" Then
            MsgBox "Thank you"
        ElseIf product2 = "" Then
            Exit Sub
        Else
            MsgBox "Please enter a valid product number"
        End If

     Loop Until LCase$(product2) = "p"

End Sub

答案 1 :(得分:0)

这是...可能的解决方法

Private Sub btnDoWhile_Click()
Dim product2 As String

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

End Sub