If ….then….Else Statements

 

Open your guessing game program from the last tutorial…

We need to make 1 change before we start…

 

Fixes before we start

 

The variable guess needs to be moved from the local subroutine level up into the general form level

 

In your code the General Area should look like

 

Dim secretnumber As Integer

Dim guess As Integer

 

And the txtguess_keypress should look like

 

Private Sub txtguess_KeyPress(KeyAscii As Integer)

' checks if answer is correct after enter key is hit.

 

If KeyAscii = 13 Then   'if i hit the enter key

  guess = txtguess.Text     'loads user guess into variable guess

  If guess > secretnumber Then lblmessage.Caption = "Too High"

  If guess < secretnumber Then lblmessage.Caption = "Too Low"

  If guess = secretnumber Then lblmessage.Caption = "You got it right"

End If

   

End Sub

 

“Notice that the guess variable is out of the subroutine and into the form level……

 

Lets get started…..

 

Add a button to the form called… “Gimme a Hint”

 

Put in under the I Give up button

 

This button will give tell us if we are close or far away from the secret number….

 

Here is the code

 

Private Sub cmdhint_Click()

'tells user if he is closer or farther away than 20 from the secret number

Dim difference As Integer

So anytime the guess is 30 bigger than the secret number, the message says “You’re cold” but if the difference is less than 30, ‘Your getting warmer.

 
 


difference = guess - secretnumber  'calculates how far the guess is off

 

If difference > 30 Then

  lblmessage.Caption = "You're so cold you are freezing"

Else

  lblmessage.Caption = "You're getting warmer"

End If

 

End Sub

 

BUT WE HAVE A HUGE PROBLEM WITH THIS….

WHAT IS THE GUESS IS 30 SMALLER THAN THE SECRET NUMBER