Secret Number
This program introduces the Option Explicit. This Option is in the
code that you use and it goes under General Declarations, not under Form_Load
or anything else, this is also a global variable meaning that it effects the entire
program. This also introduces Private Integers and Dim Integers. Both of these
are new and they are exceedingly useful and needed in programming. The Private
Integer is set under the global variable and Option Explicit; it hides it from
view. The Dim Integer is the local variable that tells the program that the
number that you guess is a real number, not some long decimal that is
impossible to think of.
1.) Open VB and start a Standard EXE
2.) Your program should have a text box,
a label and two command buttons.
The text box can be named txtGuess, there should be no text inside the box. The label should be named ‘lblMessage’, there should be no visible words in the label rectangle. The two commands should be near to ‘cmdCheckGuess’ and ‘cmdDone’. The Captions of each should be whatever you wish, though I do advise that you put the right caption on each!
2.) Open the Code
In the code window you erase everything in there first. No words. When
it is clear you can type in:
Option Explicit
Private intSecretNum As Integer ‘This is the
Private Integer and the Option Explicit as I explained at the top of the page.
Private Sub
txtGuess_Change()
lblMessage.Caption
= “”
End Sub
____________________________________________________________________________
Private Sub
cmdCheckGuess_Click()
Dim
intGuess As Integer
IntGuess =
txtGuess.Text
If
intGuess = intSecretNum Then
lblMessage
= “You guessed it!”
ElseIf
intGuess < intSecretNum Then
lblMessage = “Too low”
Else
lblMessage = “Too high”
End If
End Sub
____________________________________________________________________________
Private Sub cmdDone_Click()
Unload Me
End Sub
____________________________________________________________________________
This was the Secret Number. This program, when you play it and it works, will have you guess until you get the secret number that it chose. If the number is to high then it will tell you to guess lower. This program also introduced to you the If... Then... ElseIf... Else... Then statement. This is just what it seems like. It tell the program that
If this happens Then
this
should be the result
ElseIf this were to happen instead Then
this
would be the result
Else
if
those didn’t happen then this would be the only other alternative
End If
This is one of the easiest codes on the block, you can have just the If... Then... End If or you can have If... Then... Else... End If; really, any combination of these works. If you have problems understanding this then go here and I’ll show you a more easier way to understand, hopefully!
Anyway, there you go for this one!