Noah Xu
Noah Xu

Reputation: 167

IF statement not working in VBA

I am self-learning VBA and trying to write a little program does the following

1.asks users to enter a number between 10 to 20 in a textbox
2. When a button is clicked, the code will check the number entered in the textbox.If it is between 10 and 20, then a message will be displayed. If the number entered is not between 10 and 20 then the user will be invited to try a gain, and whatever was entered in the textbox will be erased.

Private Sub Command0_Click()
Me.Text3.SetFocus
inumber = Val(Text3.Text)
If inumber >= 10 & inumber <= 20 Then
MsgBox ("The number you entered is: ") & inumber
Else
Text3.Text = ""
MsgBox ("Please try again")
End If

End Sub

However, I don't think the else part of my codes is working. If I enter 5, it will display 5 instead of the message box. Could anyone please let me know if I have missed anything at all.

Thanks in advance. Happy Holidays.

Upvotes: 0

Views: 174

Answers (3)

Marco
Marco

Reputation: 116

Confirm: use "And" or "Or" for logical operators

Upvotes: 1

Mukul Varshney
Mukul Varshney

Reputation: 3141

Try below. & is for string concatenation in VB. And should be used in VB

Private Sub Command0_Click()
    Me.Text3.SetFocus
    inumber = Val(Text3.Text)
    If inumber >= 10 And inumber <= 20 Then
        MsgBox ("The number you entered is: ") & inumber
    Else
        Text3.Text = ""
        MsgBox ("Please try again")
    End If
End Sub

Upvotes: 1

mike morris
mike morris

Reputation: 174

If Form_customer_test >= 10 & inumber <= 20 Then

should be:

If inumber >= 10 & inumber <= 20 Then

Upvotes: 1

Related Questions