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

# 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:
number=(UpperBound-LowerBound+1
)* rnd+LowerBound

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

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)

Else

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)

Else

Label2.Caption = "Try again!"

Label2.ForeColor = RGB(255, 0, 0)

End If

End Sub