Home > Software engineering >  Visual Basic Input Box Loop if nohting
Visual Basic Input Box Loop if nohting

Time:01-16

I made a coding about calculation, there are 2 numbers in the 2 different 2 boxes, when I calculate the answer is wrong, there is a msgbox shown "Try again", if correct, the msgbox shown "you are correct", but is insert nothing or words then press enter, it will be shown error.

I want if the inputbox insert nothing then press enter, the inputbox will be shown again to restrick someone insert something into the inputbox and can not insert any words into the inputbox, if insert any words, also the inputbox will be shown again return to empty.

Does anyone can tell me how to solve this problem?

Thank you so much.


Dim a As String

        Do While True
            a = InputBox("Please enter your answer")
            If a = Val(txtnumber1.Text)   Val(txtnumber2.Text) Then
                Exit Do
            Else
                    MsgBox("Try again!!!!")
            End If
        Loop

        MsgBox("You are correct!")
    End Sub

End Class

CodePudding user response:

      Dim a As String

      Do While True
          Do While a="" Or Not IsNumeric(a)
              a = InputBox("Please enter your answer")
          Done
          If val(a) = Val(txtnumber1.Text)   Val(txtnumber2.Text) Then
              Exit Do
          Else
                  MsgBox("Try again!!!!")
          End If
      Loop

      MsgBox("You are correct!")

CodePudding user response:

InputBox in Do...Loop

Sub QnA()

    Const Title As String = "Q&A"

    Dim Answer As String
    Dim TryAgain As Long
    
    Do
        Answer = InputBox("Please enter your answer", Title, "")
        If Len(Answer) = 0 Then
            MsgBox "Nothing entered.", vbExclamation, Title
            Exit Sub
        End If
        If IsNumeric(Answer) Then
            If Val(Answer) = Val(txtnumber1.Text)   Val(txtnumber2.Text) Then
                Exit Do
            End If
        End If
        TryAgain = MsgBox("Wrong answer (""" & Answer & """). Try again?", _
            vbYesNo   vbQuestion, Title)
        If TryAgain = vbNo Then Exit Sub
    Loop
    
    MsgBox "You are correct!", vbInformation, Title

End Sub
  •  Tags:  
  • vba
  • Related