VBA example - Excel 2007: VBA If Else guess number game

VBA If Else in guess number game

In this example, We use VBA If-Else statement to test whether a guess number is correct or not. The guess number is tested against the random number from 1 to 6.
To generate random number in Excel VBA between UpperBound  and  LowerBound, we use the formula:
)* rnd+LowerBound

To run this example VBA code, you will need a Form, one TextBox, two Labels, and one CommandButton.

VBA for Excel: VBA code example of using If Else statment to detect number key pressed.

VBA code in this example:

Private Sub CommandButton1_Click()  
Dim num, rn As Integer
If TextBox1.Text <> "" Then 'checking empty text box
num = CInt(TextBox1.Text)
            MsgBox "Input your guess number!"
    TextBox1.SetFocus 'set focus to the text box  
End If
Randomize 'initialize random number generator
       rn = CInt((6 * Rnd) + 1) '((uppper-lower+1)*rnd)+lower
If num = rn Then
    Label2.Caption = "Congratulation!"    
Label2.ForeColor = RGB(0, 255, 0)
Label2.Caption = "Try again!"
Label2.ForeColor = RGB(255, 0, 0)

      End If

End Sub


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.