Visual Basic
The most popular computer language is Visual Basic for Windows (VB). More programs are written in VB than in any other computer language.
Using VB, you can easily create Windows programs that let the human use a mouse to click on icons, choose from menus, use dialog boxes, etc.
After inventing the first VB, Microsoft invented improved versions, called VB 2, VB 3, VB 4, VB 5, and VB 6. Then came a further improvement, called VB.Net 2002, then VB.Net 2003. Now Microsoft is trying to invent VB 2005 (whose codename is VB Whidbey).
You can get the current VB (which is VB.Net 2003) in three ways:
VB.Net 2003 Standard lists for $109. Discount dealers sell it for $100. But ordering that is stupid! Instead, order Microsoft Press’s Visual Basic .Net Deluxe Learning Edition Version 2003, which includes more (VB.Net 2003 Standard plus a book on how to use it) but costs just $82 total from a book discount dealer (www.amazon.com, search for 0-7356-1906-9) or $60 from Knowledgebaseinc (a reseller who markets through www.amazon.com).
Visual Studio.Net 2003 Professional lists for $1079. Discount dealers sell it for $1000. Educational resellers will sell you an academic version (if you’re an eligible student or teacher) for just $100. It includes fancy “professional” versions of 4 languages: VB, C++, C#, and J#.
To use VB.Net 2002, VB.Net 2003, or VB 2005, you need Windows XP (or Windows 2000 or Windows Server 2003). Many programmers still use VB 6 because it runs on all modern versions of Windows (95, 98, Me, XP, NT, 2000, and 2003).
This chapter explains VB 6 (which is similar to other versions of VB).
Before you read this chapter and study VB, prepare yourself! Do 3 prerequisite activities:
Learn QBASIC, which is much easier than VB. I explained QBASIC on pages 365-461. Read and practice that material.
Practice using good Windows programs (such as a Windows word-processing program), so you see how Windows programs should act. I explained good programs for modern Windows on pages 86-104 and 161-223. Read and practice whichever of those Windows programs you have access to.
Get a 17-inch monitor (or larger), and set its resolution to 1024-by-768 (or larger), so you can see all of VB’s controls well.
Visual Basic index
VB uses these commands (which resemble QBASIC’s):
VB command Page
Case "fine" 474
Circle (1000, 2000), 500 488
Close 503
Cls 488
DefInt A-Z 499
Dim x As Byte 495
Dim x(3) 500
Do 490
Do Until EOF(1) 504
Else 472
ElseIf age < 100 Then 473
End 475
End If 472
End Select 474
End Sub 463
EndDoc 467
Exit Do 491
Exit Sub 475
For x = 1 To 12 491
GoTo joe 490
If age < 18 Then Print "minor" 471
Input #1, x 503
Line (0, 0) - (1000, 2000) 488
Loop 490
Loop Until guess = "pink" 491
MsgBox "Your hair looks messy" 470
Next 491
Open "joe.txt" For Output As 1 503
Print 4 + 2 463
Print #1, "eat" 503
PrintForm 467
Private Sub Form_Load() 463
PSet (1000, 2000) 488
Randomize 501
Select Case feeling 474
Set x = Command1 497
x = 47 468
VB uses these functions (which resemble QBASIC’s):
VB function Value Page
Abs(-3.89) 3.89 494
CInt(3.9) 4 499
Date varies 497
Date$ varies 497
EOF(1) varies 504
Fix(3.89) 3 494
FormatNumber(27931.6) “27,931.60” 494
FormatPercent(.75) “75.00%” 489
InputBox("What name?") varies 470
Int(3.89) 3 494
LOF(1) varies 504
MsgBox("Fun?", vbYesNo) varies 474
Now varies 497
RGB(255, 127, 0) 32767 476
Rnd varies 501
Round(3.89) 4 494
Sgn(3.89) 1 494
Sqr(9) 3 494
Tab(6) varies 488
Time varies 497
Time$ varies 497
Timer varies 497
TypeName(4.95@) “Currency” 498
Val(InputBox("Number?")) varies 470
VarType(4.95@) 6 498
In VB, you never write “a long program”. Instead, you begin by drawing objects on the screen (as if you were using a graphics program). Then for each object, you write a little program (called a subroutine) that tells the computer how to manipulate the object. VB handles these objects:
VB object Page
CheckBox 480
ComboBox 482
CommandButton 478
Form1 463
Form2 484
Frame 483
HScrollBar 483
Label 480
Line 482
ListBox 481
Menu 485
OptionButton 479
Printer 467
Shape 482
TextBox 481
Timer 484
VScrollBar 483
Each object has properties, which you can manipulate:
VB property Popular use Page
AutoRedraw Form1 463
AutoSize Label 480
BackColor Form1 476
BorderColor Line 482
Caption Form1 475
Enabled Timer 484
FillColor Shape 482
FillStyle Shape 482
Font Form1 476
ForeColor Form1 476
Height Form1 477
Interval Timer 484
LargeChange HScrollBar 483
Left Form1 477
List ListBox 481
Max HScrollBar 483
MaxButton Form1 477
Min HScrollBar 483
MultiLine TextBox 482
MultiSelect ListBox 481
PasswordChar TextBox 482
ScrollBars TextBox 482
Selected ListBox 481
Shape Shape 482
SmallChange HScrollBar 483
StartUpPosition Form1 477
Style ComboBox 482
Text ListBox 481
Top Form1 477
Value OptionButton 479
Visible Form2 484
Width Form1 477
WindowState Form1 477
WordWrap Label 480
Fun
Let’s have fun programming!
Copy VB to the hard disk
Here’s how to copy Visual Studio (version 6, Enterprise Edition) to the hard disk. (Other versions of Visual Studio and VB are similar.)
Make sure your computer contains Windows 98 (or Me or XP) and Internet Explorer 5 (or 5.5 or 6).
Turn on the computer without any floppy or CD-ROM disks in the drives, so the computer runs Windows 98 and the computer’s bottom left corner says Start. Put Visual Studio 6.0’s Disc 1 into the CD-ROM drive. The computer will say “Visual Studio 6.0”. Press ENTER. Click “I accept the agreement”. Press ENTER.
Type the 10-digit CD key number (printed on the orange sticker at the back of the CD-ROM disk’s square case). Press TAB. Type your name. Press TAB. Type the name of your company (if any). Press ENTER four times.
You’ll see a product ID. Copy it onto the registration form that you’ll mail to Microsoft. Press ENTER three times.
Finally, the computer will copy Visual Studio to the hard disk. Click “OK”. Press ENTER. The computer will reboot itself.
The computer will say “Install MSDN”. Put the MSDN Library’s Disc 1 into the CD-ROM drive. Click “Next”. Press ENTER.
You’ll see an MSDN product ID. Copy it onto a sheet of paper. Press ENTER three times The computer will copy the MSDN Library to the hard disk. Press ENTER six times.
Remove the check mark from the “Register Now” box (by clicking it). Press ENTER.
Start VB
To start using VB, click “Start” then “Programs”. (Then click “Microsoft Visual Studio 6.0”, if you see that choice.)
Click “Microsoft Visual Basic 6.0”.
Create simple programs
Press ENTER. (That has the same effect as double-clicking “Standard EXE”).
That creates an object to manipulate: it’s a window called Form1. You see it on the screen.
On the screen’s right side, you should see a line saying:
AutoRedraw False
(If you don’t see that line, make it appear by pressing the F4 key.)
Click “AutoRedraw” then press the T key, so that line becomes:
AutoRedraw True
That tells the computer to automatically redraw Form1 each time its contents change. (If you forget to set AutoRedraw to True, the examples in this chapter won’t work!)
Double-click in the middle of the Form1 window. The double-clicking tells the computer you want to write a subroutine about that object.
The computer starts writing the subroutine for you. The computer writes:
Private Sub Form_Load()
End Sub
The top line, which is “Private Sub Form_Load()”, is the subroutine’s header. The bottom line, which is “End Sub”, is the subroutine’s footer; it marks the end of the subroutine. Between those lines, insert lines that tell the computer what to do to the object (which is the Form1 window). The lines you insert are called the subroutine’s body.
Simplest example Let’s make the Form1 window show the answer to this math problem: 4 + 2. To do that, type this line —
Print 4 + 2
so the subroutine becomes:
Private Sub Form_Load()
Print 4 + 2
End Sub
To run your program, press the F5 key. Then you see the Form1 window again. In that window, the computer has printed the answer:
6
When you’ve finished admiring that answer, stop the program by clicking the Form1 window’s X button. Then you see the subroutine again:
Private Sub Form_Load()
Print 4 + 2
End Sub
Edited example Let’s edit that subroutine, so instead of printing the answer to 4 + 2, it will print the answer to 79 + 2.
To do that, change the 4 to 79. Here’s how: click the 4’s left edge, then press the DELETE key (to delete the 4), then type 79, so the subroutine looks like this:
Private Sub Form_Load()
Print 79 + 2
End Sub
Run that program by pressing the F5 key. Then the Form1 window shows the new answer:
81
When you finish admiring that, click Form1’s X button.
Longer example Let’s make the computer print the answer to 7 - 3 (which is 4) and the answer to -26.3 + 1 (which is -25.3).
To do that, change the subroutine to this:
Private Sub Form_Load()
Print 7 - 3
Print -26.3 + 1
End Sub
To make those changes, use your mouse and keyboard (as if you’re doing word processing). If you want to delete a whole line (yank it), do this: click in the line’s middle; then while holding down the Ctrl key, tap the Y key. If you want to insert an extra line, choose one of these methods:
Method 1: click at the previous line’s end, then press ENTER.
Method 2: look at the line below; click the left edge of that line’s first character; press ENTER then .
If you make a mistake, undo it by clicking the Undo button (which is near the screen’s top, under the word “Query”.)
When typing the minus sign, make sure you hold down the SHIFT key.
Run that program by pressing the F5 key. Then the Form1 window shows the new answers:
4
-25.3
Your own examples Go ahead! Try changing the subroutine, to do different math problems instead!
Multiply To multiply, use an asterisk. So to multiply 2 by 6, type this:
Print 2 * 6
The computer will print:
12
Divide To divide, use a slash. So to divide 8 by 4, type this:
Print 8 / 4
The computer will print:
2
Congratulations You’ve written VB subroutines and created VB programs, so you’ve become a VB programmer! You can put on your résumé, “VB programmer!”
Type faster
Here are tricks that let you type faster.
You don’t need to capitalize computer words such as “Print”. The computer will capitalize them automatically when you press ENTER at the end of the line.
You must put a blank space after the word “Print” to separate “Print” from the number after it. But you don’t need to put spaces around symbols such as “+”. The computer will insert those spaces automatically when you press ENTER at the end of the line.
Instead of typing the word “Print”, you can type a question mark. When you press the ENTER key at the end of the line, the computer will automatically turn the question mark into “Print” and put a space after it. So instead of typing —
Print 4 + 2
you can type:
?4+2
Huge and tiny numbers
When dealing with huge and tiny number, be careful!
Avoid commas Do not put commas in big numbers. To write four million, do not write 4,000,000; instead, write 4000000.
The symbol # If you type a whole number that’s huge (bigger than 2147483647) or a type “a decimal point followed by just 0 or nothing” (as in 53.0 or 53.), the computer will automatically write the symbol # afterwards (when you press ENTER or run the program). That’s the computer’s way of reminding itself to treat your bizarre number carefully!
Use
decimals for big answers The computer sometimes has difficulty
handling answers bigger than 32 thousand. To avoid difficulty,
put a decimal point in any
problem whose answer might be bigger than 32 thousand.
For example, suppose you want the computer to multiply 250 by 200. Since the answer to that problem is 50 thousand, which is bigger than 32 thousand, you should put a decimal point in that problem, like this —
Print 250 * 200.0
or like this:
Print 250 * 200.
Suppose you forget to insert a decimal point, and you say just this:
Print 250 * 200
the computer will complain by saying:
Run-time error '6':
Overflow
Whenever the computer says “Run-time error”, you have 2 popular choices:
The simplest choice is to click “End”. You see the subroutine again. Fix the error (by putting a decimal point after the 200), then press F5 to rerun the program.
Another choice is to click “Debug”. You see the subroutine again, with a yellow arrow pointing to the bad line, which is highlighted in yellow. Fix the error (by putting a decimal point after the 200). Then press F5 to run the program from where you left off, at the fixed line (or press SHIFT with F5 to run the program from the beginning).
Then the computer will print the correct answer:
50000
E notation If the computer’s answer is huge (at least a quadrillion, which is 1000000000000000) or tiny (less than .1), the computer might print an E in the answer. The E means “move the decimal point”.
For example, suppose the computer says the answer to a problem is:
1.586743E+15
The E means, “move the decimal point”. The plus sign means, “towards the right”. Altogether, the E+15 means, “move the decimal point towards the right, 15 places.” So look at 1.586743, and move the decimal point towards the right, 15 places; you get 1586743000000000.
So when the computer says the answer is 1.586743E+15, the computer really means the answer is 1586743000000000, approximately. The exact answer might be 1586743000000000.2 or 1586743000000000.79 or some similar number, but the computer prints just an approximation.
Suppose your computer says the answer to a problem is:
9.23E-06
After the E, the minus sign means, “towards the left”. So look at 9.23, and move the decimal point towards the left, 6 places. You get:
.00000923
So when the computer says the answer is 9.23E-06, the computer really means the answer is:
.00000923
You’ll see E notation rarely: the computer uses it just if an answer is huge (at least a quadrillion) or tiny (tinier than .1). But when the computer does use E notation, remember to move the decimal point!
The highest number The highest number the computer can handle well is about 1E308, which is 1 followed by 308 zeros. If you try to go much higher, the computer will gripe (by saying “Overflow”).
The tiniest decimal The tiniest decimal the computer can handle accurately is 1E-309 (which is a decimal point followed by 309 digits, 308 of which are zeros). If you try to go tinier, the computer will either say 0 or give you a rough approximation.
Order of operations
What does “2 plus 3 times 4” mean? The answer depends on who you ask.
To a clerk, it means “start with 2 plus 3, then multiply by 4”; that makes 5 times 4, which is 20. But to a scientist, “2 plus 3 times 4” means something different: it means “2 plus three fours”, which is 2 + 4 + 4 + 4, which is 14.
Since computers were invented by scientists, computers think like scientists. If you type —
Print 2 + 3 * 4
the computer will think you mean “2 plus three fours”, so it will do 2 + 4 + 4 + 4 and print this answer:
14
The computer will not print the clerk’s answer, which is 20. So if you’re a clerk, tough luck!
Scientists and computers follow this rule: do multiplication and division before addition and subtraction. So if you type —
Print 2 + 3 * 4
the computer begins by hunting for multiplication and division. When it finds the multiplication sign between the 3 and the 4, it multiplies 3 by 4 and gets 12, like this:
Print 2 + 3 * 4
12
So the problem becomes 2 + 12, which is 14, which the computer prints.
For another example, suppose you type:
Print 10 - 2 * 3 + 72 / 9 * 5
The computer begins by doing all the multiplications and divisions. So it does 2 * 3 (which is 6) and does 72 / 9 * 5 (which is 8 * 5, which is 40), like this:
Print 10 - 2 * 3 + 72 / 9 * 5
6 40
So the problem becomes 10 - 6 + 40, which is 44, which is the answer the computer prints.
Parentheses You can use parentheses the same way as in algebra. For example, if you type —
Print 5 - (1 + 1)
the computer will compute 5 - 2 and print:
3
You can put parentheses inside parentheses. If you type —
Print 10 - (5 - (1 + 1))
the computer will compute 10 - (5 - 2), which is 10 - 3, and will print:
7
Multi-statement line
In your subroutine, a line can include many statements separated by colons, like this:
Print 7 - 3: Print 2 * 6: Print 8 / 4
That line means the same thing as:
Print 7 - 3
Print 2 * 6
Print 8 / 4
When you run the program, the computer will print:
4
12
2
Strings
Let’s make the computer fall in love. Let’s make it say, “I love you”.
Create this subroutine:
Private Sub Form_Load()
Print "I love you"
End Sub
The computer types the top and bottom lines for you automatically, so type just the Print line. Here’s how:
Type the word Print. Then type a blank space (by pressing the SPACE bar). Then type a quotation mark, but be careful: to type the quotation mark, you must hold down the SHIFT key. Then type these words: I love you. Then type another quotation mark.
When you run the program (by pressing F5), the computer will obey your command; it will print this message onto the Form1 window:
I love you
You can change the computer’s personality. For example, if you edit the Print command to make it become —
Print "I hate you"
the computer will reply:
I hate you
Notice that to make the computer print a message, you must put the message between quotation marks. The quotation marks make the computer copy the message without worrying about what the message means. For example, if you misspell “I love you”, and type —
Print "aieee luf ya"
the computer will still copy the message (without worrying about what it means); the computer will print:
aieee luf ya
Type faster Instead of typing —
Print "I love you"
you can type just this:
?"I love you
At the end of that line, when you press the ENTER key (or F5), the computer will automatically do three things:
The computer will change the question mark to the word Print. The computer will put a blank space after Print (and before the quotation mark). The computer will put a quotation mark at the end of the line (to match the other quotation mark).
Jargon The word “joy” consists of 3 characters: j and o and y. Programmers say that the word “joy” is a string of 3 characters.
A string is any collection of characters, such as “joy” or “I love you” or “aieee luf ya” or “76 trombones” or “GO AWAY!!!” or “xypw exr///746”. The computer will print whatever string you wish, but remember to put the string in quotation marks.
Strings
versus numbers The computer can handle two types of expressions: strings and numbers. Put
strings (such as “joy” and “I love you”) in quotation marks. Numbers (such as
4 + 2) do not go in quotation marks.
Accidents Suppose you accidentally put the number 2 + 2 in quotation marks, like this:
Print "2 + 2"
The quotation marks make the computer think “2 + 2” is a string instead of a number. Since the computer thinks “2 + 2” is a string, it copies the string without analyzing what it means; the computer will print:
2 + 2
It will not print 4.
Suppose you want the computer to print the word “love” but you accidentally forget to put the string “love” in quotation marks, and type this instead:
Print love
Since you forgot the quotation marks, the computer is confused. Whenever the computer is confused, it either gripes at you or prints nothing or prints a zero. In this particular example, when you run the program the computer will print nothing: the Form1 window will stay blank. So if you incorrectly tell the computer to proclaim its love, it will give you a blank look.
Longer subroutines You can program the computer say it’s madly in love with you!
Let’s make the computer say:
I love you.
You turned me on.
Let's get married!
To make the computer say all that, just run this subroutine:
Private Sub Form_Load()
Print "I love you."
Print "You turned me on."
Print "Let's get married!"
End Sub
The computer typed the top and bottom lines; just type the Print lines then press F5. Try it!
To have even more fun, run this program:
Private Sub Form_Load()
Print "I long"
Print 2 + 2
Print "U"
End Sub
It makes the computer print “I long”, then print the answer to 2+2 (which is 4), then print “U”. So altogether, the computer prints:
I long
4
U
Yes, the computer says it longs for you!
Tricky printing
Printing can be tricky! Here are the tricks.
Indent Suppose you want the computer to print this letter onto Form1:
Dear Joan,
Thank you for the beautiful
necktie. Just one problem--
I don't wear neckties!
Love,
Fred the Hippie
This subroutine prints it:
Private Sub Form_Load()
Print "Dear Joan,"
Print " Thank you for the beautiful"
Print "necktie. Just one problem--"
Print "I don't wear neckties!"
Print " Love,"
Print " Fred the Hippie"
End Sub
Each Print line contains two quotation marks. To make the computer indent a line, put blank spaces AFTER the first quotation mark.
Blank lines Life consists of some joy, some sorrow, and some numb emptiness. To express those feelings, run this subroutine:
Subroutine What the computer will do
Private Sub Form_Load() Start the subroutine.
Print "joy" Print “joy”.
Print Print a blank empty line, underneath “joy”.
Print "sorrow" Print “sorrow”.
End Sub End the subroutine.
Altogether, the computer will print:
joy
sorrow
Semicolons Run this subroutine:
Private Sub Form_Load()
Print "fat";
Print "her"
End Sub
The first Print line (saying to print “fat”) ends with a semicolon. The semicolon makes the computer print the next item on the same line; so the computer will print “her” on the same line, like this:
father
This line shows what happens to an evil king on a boat:
Print "sin"; "king"
It makes the computer print “sin” and then print “king” on the same line, like this:
sinking
Spaces after numbers Try typing this command:
Print -3; "might be my favorite number"
Whenever the computer prints a NUMBER, it prints a blank space afterwards; so the computer will print a blank space after -3, like this:
-3 might be my favorite number
space
Spaces before positive numbers This command tells what to put in your coffee:
Print 7; "do"; "nuts"
The computer prints 7 and “do” and “nuts”. Since 7 is a number, the computer prints a blank space after the 7. The computer prints another blank space BEFORE every number that’s positive; so the computer prints another blank space before the 7, like this:
7 donuts
spaces
Hey, if you’re feeling cool, maybe this command expresses your feelings:
Print "the temperature is"; 4 + 25; "degrees"
The computer prints “the temperature is”, then 4 + 25 (which is 29), then “degrees”. Since 29 is a positive number, the computer prints a blank space before and after the 29:
the temperature is 29 degrees
spaces
Fix the negative numbers Use this command if you’re even colder:
Print "the temperature is"; 4 - 25; "degrees"
The computer prints “the temperature is”, then 4 - 25 (which is -21), then “degrees”. Since -21 is a number, the computer prints a space after it; but since -21 is not positive, the computer does not print a space before it. The computer prints:
the temperature is-21 degrees
no space space
Yuk! That looks ugly! It would look prettier if there were a space before the -21. To insert a space, put the space inside quotation marks:
Print "the temperature is "; 4 - 25; "degrees"
inserted space, before the quotation mark
Then the computer will print:
the temperature is -21 degrees
inserted space
Multiple calculations By using semicolons, you can make the computer do many calculations at once.
For example, this command makes the computer do 6+2, 6-2, 6*2, and 6/2, all at once:
Print 6 + 2; 6 - 2; 6 * 2; 6 / 2
That makes the computer print the four answers:
8 4 12 3
The computer prints spaces between the answers, because the computer prints a space after every number (and an additional space before every number that’s positive).
Print a quotation mark The symbol for inches is ". Let’s make the computer print this sentence:
The nail is 2" long.
This Print command does not work:
Print "The nail is 2" long."
When the computer sees the quotation mark after 2, it mistakenly thinks that quotation mark is paired with the quotation mark before “The”, then gets totally confused.
Here’s the correct way to write that line:
Print "The nail is 2"" long."
The symbol "" means: print a quotation mark. That Print line makes the computer print:
The nail is 2" long.
Here’s the rule: to print the quotation mark ("), you must put the symbol "" in your Print statement.
Let’s make the computer print this sentence:
I saw "Hamlet" last night.
To print the quotation mark before “Hamlet”, you must type "". To print the quotation mark after “Hamlet”, you must type "" Here’s the solution:
Print "I saw ""Hamlet"" last night."
Print on paper If you say Printer.Print instead of just Print, the computer will print on paper instead of on your screen.
For example, if you want the computer to compute 2 + 2 and print the answer on paper, create this subroutine:
Private Sub Form_Load()
Printer.Print 2 + 2
End Sub
When you run that program (by pressing the F5 key), the computer will compute 2 + 2 and prepare to print the answer (which is 4) onto paper. The actual printing will occur when you finish running the program (by clicking its X button).
The printing will succeed just if you already put paper in the printer and turned the printer’s power on.
If you say Print 2 + 2, the computer prints the answer (4) onto the screen. If you say Printer.Print 2 + 2, the computer prints 4 onto paper instead. If you want to print the answer onto the screen and also onto paper, say Print and also Printer.Print, like this:
Print 2 + 2
Printer.Print 2 + 2
That technique is called dual printing because it makes the computer print in two places: on the screen and on paper.
If you tell the computer to print onto paper, the computer prints to the RAM first, in a part of the RAM called the Printer object. The computer doesn’t copy from the Printer object to the printer until you finish running your program (by clicking its X button) or give a Printer.EndDoc command (in your subroutine).
Here’s another way to accomplish dual printing:
Print "Your eyes are haunting"
Print "Your smile is gentle"
PrintForm
The first two lines print this message onto Form1, which is on the screen:
Your eyes are haunting
Your smile is gentle
The PrintForm line copies Form1 onto paper; so the printer will print “Your eyes are haunting” and “Your smile is gentle”, all in a gray box (since Form1 is a gray box). The printing occurs immediately. It works just if you remembered to say “AutoRedraw T” (as I warned you on page 463) and didn’t give any Printer.Print commands.
Final steps
When you finish playing with your program, here’s what to do.
Make sure you see the subroutine you typed. (If you see Form1’s window instead, close that window by clicking its X button.)
Save If you like the program you created and want to save it on disk, click the Save Project button. (It looks like a floppy disk. It’s near the screen’s top, below the word “Format”.)
If you haven’t done so already, invent a name for your program (such as “Funmaker”): type the name, press ENTER, type the name again, and press ENTER again. (During that process, if the computer complains that the name “already exists”, press ENTER then try a different name instead.)
That process makes the computer create two files (Funmaker.frm and Funmaker.vbp) and put them in your hard disk’s VB98 folder (which is in the Microsoft Visual Studio folder, which is in the Program Files folder).
If the computer asks “Add this project to SourceSafe?”, click “No”.
Afterwards, if you make further changes to the program, click the Save Project button again to save them.
New If you’re tired of working on a program and want to start inventing a different program instead, click “File” then “New Project”.
(If you didn’t save the previous program, the computer will ask “Save changes?” If you want to save the previous program, click “Yes” and answer any questions the computer asks about the program’s name; otherwise, click “No”.)
Eventually, the computer will say “New Project”.
Press ENTER. (That has the same effect as double-clicking Standard EXE.) Click “AutoRedraw”, then press the T key.
Exit When you finish using VB, click the X button that’s in the screen’s top right corner.
Open When you start using VB, you typically press ENTER (which has the same effect as double-clicking “Standard EXE”). Instead of pressing ENTER, try clicking “Existing”. You see a list of programs you created. Double-click the program you want to return to.
Some parts of your program will be missing from your screen. To make sure you see them all, do this:
Near the screen’s top right corner, you see the word “Form1”. Double-click it.
Click “View” (near the screen’s top left corner) then “Object” then “View” again then “Code”.
Make .exe Try this experiment. Create a program and save it. On the File menu, you see a choice saying “Make”; for example, if you named your program “Funmaker”, you see a choice saying “Make Funmaker.exe”. Choose that, then press ENTER. Then click the Save Project button again. That makes the computer put a file called Funmaker.exe into your VB98 folder.
Congratulations! You’ve made an .exe file that can be run without going into Visual Basic!
Here’s how to run that file:
Exit from Visual Basic. Double-click “My Computer” then “C:” then “Program Files” then “Microsoft Visual Studio” then “VB98”. You see four icons for the program you created; double-click the first one.
The program will run. While the program runs, you see the program’s Form1 window, which shows the program’s results. (You do not see the commands you typed in the program’s subroutine.)
When you finish admiring the program’s results, close the program’s Form1 window (by clicking its X button). Then close all other windows (by clicking their X buttons).
Variables
A letter can stand for a number. For example, x can stand for the number 47, as in this subroutine:
Private Sub Form_Load()
x = 47
Print x + 2
End Sub
The second line says x stands for the number 47. In other words, x is a name for the number 47.
The next line says to print x + 2. Since x is 47, the x + 2 is 49; so the computer will print 49. That’s the only number the computer will print; it will not print 47.
Jargon
A letter that stands for a number is called a numeric variable. In that subroutine, x is a numeric variable; it stands for the number 47. The value of x is 47.
In that subroutine, the statement “x = 47” is called an assignment statement, because it assigns 47 to x.
A variable is a box
When you run that subroutine, here’s what happens inside the computer.
The computer’s random-access memory (RAM) consists of electronic boxes. When the computer encounters the line “x = 47”, the computer puts 47 into box x, like this:
box x 47
Then when the computer encounters the line “Print x + 2”, the computer prints what’s in box x, plus 2; so the computer prints 49.
Faster typing
Instead of typing —
x = 47
you can type just this:
x=47
At the end of that line, when you press the ENTER key, the computer will automatically put spaces around the equal sign.
More examples
Here’s another subroutine body:
y = 38
Print y - 2
The top line says y is a numeric variable that stands for the number 38. The bottom line says to print y - 2. Since y is 38, the y - 2 is 36; so the computer will print 36.
Another example:
b = 8
Print b * 3
The top line says b is 8. The bottom line says to print b * 3, which is 8 * 3, which is 24; so the computer will print 24.
One variable can define another:
n = 6
d = n + 1
Print n * d
The top line says n is 6. The next line says d is n + 1, which is 6 + 1, which is 7; so d is 7. The bottom line says to print n * d, which is 6 * 7, which is 42; so the computer will print 42.
Changing a value
A value can change:
k = 4
k = 9
Print k * 2
The top line says k’s value is 4. The next line changes k’s value to 9, so the bottom line prints 18.
When you run that subroutine, here’s what happens inside the computer’s RAM. The top line (k = 4) makes the computer put 4 into box k:
box k 4
The next line (k = 9) puts 9 into box k. The 9 replaces the 4:
box k 9
That’s why the bottom line (Print k * 2) prints 18.
Decimal points
On page 464, I said to “put a decimal point in any problem whose answer might be bigger than 32 thousand.” Here’s good news: when using a variable, the computer inserts any needed decimal point automatically, so you don’t have to worry about it!
For example, suppose you say:
x = 200
Print 250 * x
When the computer encounters that Print line, it will change x from 200 to 200.0, to handle results bigger than 32000. It will multiply 250 by 200.0 and print the correct answer:
50000
Hassles
When writing an equation (such as x = 47), here’s what you must put before the equal sign: the name of just one box (such as x). So before the equal sign, put one variable:
Allowed: d = n + 1 (d is one variable)
Not allowed: d - n = 1 (d - n is two variables)
Not allowed: 1 = d - n (1 is not a variable)
The variable on the left side of the equation is the only one that changes. For example, the statement d = n + 1 changes the value of d but not n. The statement b = c changes the value of b but not c:
b = 1
c = 7
b = c
Print b + c
The third line changes b, to make it equal c; so b becomes 7. Since both b and c are now 7, the bottom line prints 14.
“b = c” versus “c = b” Saying “b = c” has a different effect from “c = b”. That’s because “b = c” changes the value of b (but not c); saying “c = b” changes the value of c (but not b).
Compare these subroutines:
b = 1 b = 1
c = 7 c = 7
b = c c = b
Print b + c Print b + c
In the left subroutine (which you saw before), the third line changes b to 7, so both b and c are 7. The bottom line prints 14.
In the right-hand subroutine, the third line changes c to 1, so both b and c are 1. The bottom line prints 2.
While you run those subroutines, here’s what happens inside the computer’s RAM. For both subroutines, the top two lines do this:
box b 1
box c 7
In the left program, the third line makes the number in box b become 7 (so both boxes contain 7, and the bottom line prints 14). In the right program, the third line makes the number in box c become 1 (so both boxes contain 1, and the bottom line prints 2).
When to use variables
Here’s a practical example of when to use variables.
Suppose you’re selling something that costs $1297.43, and you want to do these calculations:
multiply $1297.43 by 2
multiply $1297.43 by .05
add $1297.43 to $483.19
divide $1297.43 by 37
To do those four calculations, you could run this subroutine:
Print 1297.43 * 2; 1297.43 * .05; 1297.43 + 483.19; 1297.43 / 37
But that subroutine’s silly, since it contains the number 1297.43 four times. This subroutine’s briefer, because it uses a variable:
c = 1297.43
Print c * 2; c * .05; c + 483.19; c / 37
So whenever you need to use a number several times, turn the number into a variable, which will make your subroutine briefer.
String variables
A string is any collection of characters, such as “I love you”. Each string must be in quotation marks.
A letter can stand for a string:
x = "I love you"
Print x
The top line says x stands for the string “I love you”. The bottom line prints:
I love you
In that subroutine, x is a variable. Since it stands for a string, it’s called a string variable.
If you’re paranoid, you’ll love this subroutine:
t = "They're laughing at you!"
Print t
Print t
Print t
The top line says t stands for the string “They’re laughing at you!” The later lines make the computer print:
They're laughing at you!
They're laughing at you!
They're laughing at you!
Spaces between strings
Examine this subroutine:
s = "sin"
k = "king"
Print s; k
The bottom line says to print “sin” and then “king”, so the computer will print:
sinking
Let’s make the computer leave a space between “sin” and “king”, so the computer prints:
sin king
To make the computer leave that space, use one of these methods.…
Method 1. Instead of saying —
s = "sin"
make s include a space:
s = "sin "
Method 2. Instead of saying —
k = "king"
make k include a space:
k = " king"
Method 3. Instead of saying —
Print s; k
say to print s, then a space, then k:
Print s; " "; k
Since the computer will automatically insert the semicolons, you can type just this —
Print s " " k
or even type just this —
Print s" "k
or even type just this:
?s" "k
When you press the ENTER key at the end of that line, the computer will automatically convert it to:
Print s; " "; k
Nursery rhymes
The computer can recite nursery rhymes:
p = "Peas porridge "
Print p; "hot!"
Print p; "cold!"
Print p; "in the pot,"
Print "Nine days old!"
The top line says p stands for “Peas porridge ”. The later lines make the computer print:
Peas porridge hot!
Peas porridge cold!
Peas porridge in the pot,
Nine days old!
This subroutine prints a fancier rhyme:
h = "Hickory, dickory, dock! "
m = "THE MOUSE (squeak! squeak!) "
c = "THE CLOCK (tick! tock!) "
Print h
Print m; "ran up "; c
Print c; "struck one"
Print m; "ran down"
Print h
The top three lines define h, m, and c. The later lines make the computer print:
Hickory, dickory, dock!
THE MOUSE (squeak! squeak!) ran up THE CLOCK (tick! tock!)
THE CLOCK (tick! tock!) struck one
THE MOUSE (squeak! squeak!) ran down
Hickory, dickory, dock!
Long variable names
A numeric variable’s name can be a letter (such as x) or a longer combination of characters, such as:
CityPopulationIn2001
For example, you can type:
CityPopulationIn2001 = 30716
CityPopulationIn2002 = CityPopulationIn2001 + 42
Print CityPopulationIn2002
The computer will print:
30758
The variable’s name can be as long as you wish: up to 255 characters! The name’s first character must be a letter; the remaining characters can be letters or digits. The computer ignores capitalization: it assumes that CityPopulationIn2001 is the same as citypopulationin2001.
The name must not be a word having a special meaning to the computer. For example, the name cannot be “Print”.
Beginners are usually too lazy to type long variable names, so beginners use variable names that are short. But when you become a pro and write a long, fancy program containing hundreds of lines and hundreds of variables, you should use long variable names to help you remember each variable’s purpose.
In this book, I’ll use short variable names in short programs (so you can type those programs quickly), and long variable names in long programs (so you can keep track of which variable is which).
Pop-up boxes
Here’s how to make a box appear suddenly on your screen.
Message box
Into any subroutine, you can insert this line:
MsgBox "Warning: your hair looks messy today"
When the computer runs the program and encounters that line, the computer suddenly creates a message box (a window containing a short message), which covers Form1 and contains this message: “Warning: your hair looks messy today”. The computer automatically makes the window be wide enough to include the whole message and be centered on the screen. When that window suddenly appears, the computer also rings a bell to get the human’s attention.
The window includes an OK button. When the human finishes reading the message, the human must click that OK button (or press ENTER) to make the window go away.
After the window goes away, Form1 reappears and the computer continues running the rest of the program (including any lines below the MsgBox line). Form1 remains on the screen until the human clicks Form1’s X button to end the program.
To make the message box fancier, say vbExclamation, like this:
MsgBox "Warning: your hair looks messy today", vbExclamation
That makes the message box window include an exclamation icon (an exclamation point in a yellow triangle).
You can choose from 4 icons:
Icon Command
! (in a yellow triangle) vbExclamation
X (in a red circle) vbCritical
i (in a cartoon bubble) vbInformation
? (in a cartoon bubble) vbQuestion
Input box
For a wild experience, type this subroutine:
Private Sub Form_Load()
x = InputBox("What is your name?")
Print "I adore anyone whose name is "; x
End Sub
Run the program (by pressing F5). Here’s what happens…
The InputBox line makes the computer suddenly creates an input box, which is a window letting the human type info into the computer. That window covers Form1 and is slightly above the screen’s center. It contains this prompt: “What is your name?” It also contains a white box (into which the human can type a response) and an OK button.
The computer waits for the human to type a response. When the human finishes typing a response, the human must click the OK button (or press ENTER) to make the window go away.
Then Form1 reappears and the computer makes x be whatever the human typed. For example, if the human typed —
Maria
x will be Maria. Then the Print line will make the computer print:
I adore anyone whose name is Maria
College admissions This subroutine makes the computer print a letter admitting you to the college of your choice:
Private Sub Form_Load()
college = InputBox("What college would you like to enter?")
Print "Congratulations!"
Print "You have just been admitted to "; college
Print "because it fits your personality."
Print "I hope you go to "; college; "."
Print " Respectfully yours,"
Print " The Dean of Admissions"
End Sub
Run the program (by pressing F5). An input box suddenly appears, asking “What college would you like to enter?” Type your answer (then click OK or press ENTER).
For example, if you type —
Harvard
the college will be Harvard and so the computer will print:
Congratulations!
You have just been admitted to Harvard
because it fits your personality.
I hope you go to Harvard.
Respectfully yours,
The Dean of Admissions
If you type this instead —
Hell
the computer will print:
Congratulations!
You have just been admitted to Hell
because it fits your personality.
I hope you go to Hell.
Respectfully yours,
The Dean of Admissions
All the printing is onto Form1. If you want to print onto paper instead, change each “Print” to “Printer.Print”.
Numeric input To input a string, you’ve learned to say InputBox. To input a number, say InputBox but also say Val, to emphasize that you want the computer to produce a numeric value.
For example, this subroutine asks for your two favorite numbers and prints their sum:
Private Sub Form_Load()
x = Val(InputBox("What is the first number?"))
y = Val(InputBox("What is the second number?"))
Print x + y
End Sub
When you run the program (by pressing F5), the computer asks “What is the first number?”, waits for you to type it, and calls it x. Then the computer asks “What is the second number?”, waits for you to type it, and calls it y. Then the computer prints the sum of the numbers. For example, if the first number was 7 and the second number was 2, the computer will print the sum:
9
In that program, if you accidentally omit each Val, the computer will think x and y are strings instead of numbers, so the computer will add the string “7” to the string “2” and print this longer string:
72
Predict your future This subroutine makes the computer predict your future:
Private Sub Form_Load()
y = Val(InputBox("In what year were you born?"))
Print "In the year 2020, you'll turn"; 2020 - y; "years old."
End Sub
When you run the program, the computer asks, “In what year were you born?” If you answer —
1962
y will be the numeric value 1962, and the computer will correctly print:
In the year 2020, you'll turn 58 years old.
Prices Suppose you’re selling tickets to a play. Each ticket costs $2.79. (You decided $2.79 would be a nifty price, because the cast has 279 people.) These lines find the price of multiple tickets:
t = Val(InputBox("How many tickets?"))
Print "The total price is $"; t * 2.79
Conversion These lines convert feet to inches:
f = Val(InputBox("How many feet?"))
Print f; " feet ="; f * 12; "inches"
When you run the program, the computer asks “How many feet?” If you answer —
3
the computer will print:
3 feet = 36 inches
Trying to convert to the metric system? These lines convert inches to centimeters:
i = Val(InputBox("How many inches?"))
Print i; " inches ="; i * 2.54; "centimeters"
Nice day today, isn’t it? These lines convert the temperature from Celsius to Fahrenheit:
c = Val(InputBox("How many degrees Celsius?"))
Print c; " degrees Celcius ="; c * 1.8 + 32; "degrees Fahrenheit"
When you run the program, the computer asks “How many degrees Celsius?” If you answer —
20
the computer will print:
20 degrees Celsius = 68 degrees Fahrenheit
See, you can write the Guide yourself! Just hunt through any old math or science book, find any old formula (such as f = c * 1.8 + 32), and turn it into a program.
Control statements
A subroutine is a list of statements that you want the computer to perform. Here’s how to control which statements the computer performs, and when, and in what order.
If
This subroutine makes the computer discuss the human’s age:
Private Sub Form_Load()
age = Val(InputBox("How old are you?"))
Print "I hope you enjoy being "; age
End Sub
When that program is run (by pressing F5), the computer asks “How old are you?” and waits for the human’s reply. For example, if the human says —
15
the age will be 15. Then the computer will print:
I hope you enjoy being 15
Let’s make that subroutine fancier, so if the human is under 18 the computer will also say “You are still a minor”. To do that, just add a line saying —
If age < 18 Then Print "You are still a minor"
so the subroutine looks like this:
Private Sub Form_Load()
age = Val(InputBox("How old are you?"))
Print "I hope you enjoy being "; age
If age < 18 Then Print "You are still a minor"
End Sub
For example, if the human runs the program and says —
15
the computer will print:
I hope you enjoy being 15
You are still a minor
If instead the human says —
25
the computer will print just:
I hope you enjoy being 25
In that program, the most important line is:
If age < 18 Then Print "You are still a minor"
That line contains the words If and Then. Whenever you say “If”, you must also say “Then”. Do not put a comma before “Then”. What comes between “If” and “Then” is called the condition; in that example, the condition is “age < 18”. If the condition is true (if the age is really less than 18), the computer does the action, which comes after the word “Then” and is:
Print "You are still a minor"
Else Let’s teach the computer how to respond to adults.
Here’s how to program the computer so that if the age is less than 18, the computer will say “You are still a minor”, but if the age is not less than 18 the computer will say “You are an adult” instead:
Private Sub Form_Load()
age = Val(InputBox("How old are you?"))
Print "I hope you enjoy being "; age
If age < 18 Then Print "You are still a minor" Else Print "You are an adult"
End Sub
In programs, the word “Else” means “otherwise”. That program’s If line means: if the age is less than 18, then print “You are still a minor”; otherwise (if the age is not less than 18), print “you are an adult”. So the computer will print “You are still a minor” or else print “You are an adult”, depending on whether the age is less than 18.
Try running that program! If you say you’re 50 years old, the computer will reply by saying:
I hope you enjoy being 50
You are an adult
Multi-line If If the age is less than 18, here’s how to make the computer print “You are still a minor” and also print “Ah, the joys of youth”:
If age < 18 Then Print "You are still a minor": Print "Ah, the joys of youth"
Here’s a more sophisticated way to say the same thing:
If age < 18 Then
Print "You are still a minor"
Print "Ah, the joys of youth"
End If
That sophisticated way (in which you type 4 short lines instead of a single long line) is called a multi-line If (or a block If).
In a multi-line If:
The top line must say If and Then (with nothing after Then).
The middle lines should be indented; they’re called the block and typically say Print. The indentation is optional but helps you see clearly how your program is organized; it turns your program into an outline.
The bottom line must say End If.
Here’s how to indent the Print lines in that block:
To indent the first Print line, press the TAB key at the line’s beginning.
The computer will automatically indent the second Print line, the same amount as the first.
The computer will automatically try to indent the next line also (which says End If). At that line’s beginning, press the BACKSPACE key to unindent the line.
In the middle of a multi-line If, you can say Else:
If age < 18 Then
Print "You are still a minor"
Print "Ah, the joys of youth"
Else
Print "You are an adult"
Print "We can have adult fun"
End If
That means: if the age is less than 18, then print “You are still a minor” and “Ah, the joys of youth”; otherwise (if age not under 18) print “You are an adult” and “We can have adult fun”.
ElseIf Let’s say this:
If age is under 18, print “You’re a minor”.
If age is not under 18 but is under 100, print “You’re a typical adult”.
If age is not under 100 but is under 125, print “You’re a centenarian”.
If age is not under 125, print “You’re a liar”.
Here’s how:
If age < 18 Then
Print "You're a minor"
ElseIf age < 100 Then
Print "You're a typical adult"
ElseIf age < 125 Then
Print "You're a centenarian"
Else
Print "You're a liar"
End If
“ElseIf” is one word. Type “ElseIf”, not “Else If”. If you accidentally type “Else If”, the computer will gripe.
Different relations You can make the If clause very fancy:
IF clause Meaning
If age = 18 If age is 18
If age < 18 If age is less than 18
If age > 18 If age is greater than 18
If age <= 18 If age is less than or equal to 18
If age >= 18 If age is at least 18 (greater than or equal to 18)
If age <> 18 If age is not 18
If sex = "male" If sex is “male”
If sex < "male" If sex is a word (such as “female”) that comes before “male” in the dictionary
If sex > "male" If sex is a word (such as “neuter”) that comes after “male” in the dictionary
In the If statement, the symbols =, <, >, <=, >=, and <> are called relations.
When writing a relation, mathematicians and computerists habitually put the equal sign last:
Right Wrong
<= =<
>= =>
When you press the ENTER key at the end of the line, the computer will automatically put your equal signs last: the computer will turn any “=<” into “<=”; it will turn any “=>” into “<=”.
To say “not equal to”, say “less than or greater than”, like this: <>.
Or The computer understands the word Or. For example, here’s how to say, “If age is either 7 or 8, print the word wonderful”:
If age = 7 Or age = 8 Then Print "wonderful"
That example is composed of two conditions: the first condition is “x = 7”; the second condition is “x = 8”. Those two conditions combine, to form “x = 7 Or x = 8”, which is called a compound condition.
If you use the word Or, put it between two conditions.
Right: If age = 7 Or age = 8 Then Print "wonderful" (“age = 7” and “age = 8” are conditions)
Wrong: If age = 7 Or 8 Then Print "wonderful" (“8” is not a condition)
And The computer understands the word And. Here’s how to say, “If age is more than 5 and less than 10, print you get hamburgers for lunch”:
If age > 5 And age < 10 Then Print "you get hamburgers for lunch"
Here’s how to say, “If score is at least 60 and less than 65, print you almost failed”:
IF score >= 60 And score < 65 Then Print "you almost failed"
Here’s how to say, “If n is a number from 1 to 10, print that’s good”:
IF n >= 1 And n <= 10 Then Print "that's good"
Yes/no message box
Let’s make the computer ask, “Do you love me?” If the human says “Yes”, let’s make the computer say “I love you too!” If the human says “No”, let’s make the computer say “I don’t love you either!”
This subroutine accomplishes that goal:
Private Sub Form_Load()
response = InputBox("Do you love me?")
If response = "yes" Then
Print "I love you too!"
Else
Print "I don't love you either!"
End If
End Sub
But that subroutine has a flaw: what if the human types neither “yes” nor “no”? Instead of typing “yes”, what if the human types “YES” or “Yes” or “yeah” or “yep” or “yessiree” or just “y” or “certainly” “I love you tremendously” or “not sure”? In those situations, since the human didn’t type simply “yes”, the computer will say “I don’t love you either!”, which is inappropriate.
The problem with that subroutine is it gives the human too many choices: it lets the human type anything in the input box.
To make sure the computer reacts appropriately to the human, give the human fewer choices. Restrict the human to choosing just Yes or No. Here’s how: show the human a Yes button and a No button, then force the human to click one of them. This subroutine accomplishes that:
Private Sub Form_Load()
If MsgBox("Do you love me?", vbYesNo) = vbYes Then
Print "I love you too!"
Else
Print "I don't love you either!"
End If
End Sub
The MsgBox line makes the computer create a message box saying “Do you love me?” A normal message box contains an OK button, but vbYesNo makes this be a yes/no message box instead (which contains Yes and No buttons instead of an OK button).
If the human clicks the Yes button, the subroutine makes the computer print “I love you too!” If the human does otherwise (by clicking the No button), the computer prints “I don’t love you either!”
Select
Let’s turn your computer into a therapist!
To do that, make the computer ask the patient “How are you?” and let the patient type whatever words the patient wishes. Just begin the subroutine like this:
Private Sub Form_Load()
feeling = InputBox("How are you?")
That makes the computer ask “How are you?” and makes the patient’s response be called the feeling.
Make the computer continue the conversation as follows:
If the patient said “fine”, print “That’s good!”
If the patient said “lousy” instead, print “Too bad!”
If the patient said anything else instead, print “I feel the same way!”
To accomplish all that, you can use a multi-line If:
If feeling = "fine" Then
Print "That's good!"
ElseIf feeling = "lousy" Then
Print "Too bad!"
Else
Print "I feel the same way!"
End If
Instead of typing that multi-line If, you can type this
Select statement
instead, which is briefer and simpler:
Select Case feeling
Case "fine"
Print "That's good!"
Case "lousy"
Print "Too bad!"
Case Else
Print "I feel the same way!"
End Select
Like a multi-line If, a Select statement consumes several lines. The top line of that Select statement tells the computer to analyze the feeling and Select one of the cases from the list underneath. That list is indented and says:
In the case where the feeling is “fine”,
print “That’s good!”
In the case where the feeling is “lousy”,
print “Too bad!”
In the case where the feeling is anything else,
print “I feel the same way!”
The bottom line of every Select statement must say End Select.
Complete subroutine Here’s a complete subroutine:
Private Sub Form_Load()
feeling = InputBox("How are you?")
Select Case feeling
Case "fine"
Print "That's good!"
Case "lousy"
Print "Too bad!"
Case Else
Print "I feel the same way!"
End Select
Print "I hope you enjoyed your therapy. Now you owe $50."
End Sub
The InputBox line makes the computer ask the patient, “How are you?” The next several lines are the Select statement, which makes the computer analyze the patient’s answer and print “That’s good!” or “Too bad!” or else “I feel the same way!”
Regardless of what the patient and computer said, that subroutine’s bottom Print line always makes the computer end the conversation by printing:
I hope you enjoyed your therapy. Now you owe $50.
In that program, try changing the strings to make the computer print smarter remarks, become a better therapist, and charge even more money.
Fancy cases You can create fancy cases:
Statement Meaning
Case "fine" If it’s “fine”
Case "fine", "lousy" If it’s “fine” or “lousy”
Case 6 If it’s 6
Case 6, 7, 18 If it’s 6 or 7 or 18
Case Is < 18 If it’s less than 18
Case Is > 18 If it’s greater than 18
Case Is <= 18 If it’s less than or equal to 18
Case Is >= 18 If it’s at least 18 (greater than or equal to 18)
Case 6, 7, Is >=18 If it’s 6 or 7 or at least 18
Case 10 to 100 If it’s between 10&100 (at least 10 but no more than 100)
Case 6, 10 to 100 If it’s 6 or between 10&100
Exit Sub
To make the computer skip the bottom part of your subroutine, say Exit Sub, like this:
Private Sub Form_Load()
Print "I love the company president"
Exit Sub
Print "as much as stale bread"
End Sub
When you run that program (by pressing F5), the computer will print “I love the company president” and then exit from the subroutine, without printing “as much as stale bread”. The computer will print just:
I love the company president
Suppose you write a subroutine that prints a long message, and you want to run the program several times (so several of your friends get the message). If one of your friends would be offended by the end of your message, send that friend an abridged message! Here’s how: put Exit Sub above the part of the message that you want the computer to omit.
End
Here’s a simple subroutine:
Private Sub Form_Load()
MsgBox "Warning: your hair looks messy today"
End Sub
When human runs the program, the computer creates a message box saying “Warning: your hair looks messy today”. Then the computer waits for the human to click the message box’s OK button.
When the human clicks the OK button, the message box disappears. Then the computer is supposed to do any remaining lines in the subroutine. But there are no lines remaining to be done. So the computer just waits for the human to close the program by clicking its X button.
What if the human is too stupid to know to click the X button? Instead of clicking the X button, what if the human just keeps waiting to see whether the computer will do something? The situation is stupid: the computer waits for the human to click the X button, while the human waits for the computer to say what to do next.
To end such confusion, say End near your subroutine’s bottom, like this:
Private Sub Form_Load()
MsgBox "Warning: your hair looks messy today"
End
End Sub
That End line makes the computer stop running the program and automatically click the X button.
Long programs While running a long program, the computer should occasionally ask whether the human wants to continue. To make the computer ask that, insert this line:
If MsgBox("Do you want to continue?", vbYesNo) = vbNo Then End
That line creates a yes/no message box asking “Do you want to continue?” If the human clicks the No button, the program will end (and the computer will automatically click the program’s X button).
Properties
You can change Form1’s properties.
Caption
The top of Form1’s window normally says “Form1”, but you can make it say something else instead. For example, you can make it say “Results” or “Payroll results” or “Mary’s window” or “Fun stuff” or “Hey, I’m a funny window full of fun stuff!” You can make the top of the window say whatever you wish! That’s called the window’s caption.
Let’s make the caption become “Fun stuff”. You can do that in two ways.…
Equation method One way to make the caption become “Fun stuff” is to insert this equation in Form1’s subroutine:
Caption = "Fun stuff"
Then the caption will change to “Fun stuff” when you run the program.
Property-list method Here’s a more sophisticated way to change the caption to “Fun stuff”.
At the screen’s right side, you should see a window called “Properties — Form1”. (If you accidentally erased that window, make it reappear by pressing the F4 key.)
In that window, you can see this property list:
Property Value
(Name) Form1
Appearance 1 - 3D
AutoRedraw False
BackColor &H8000000F&
BorderStyle 2 - Sizable
Caption Form1
ClipControls True
ControlBox True
DrawMode 13 - Copy Pen
DrawStyle 0 - Solid
DrawWidth 1
Enabled True
FillColor &H00000000&
FillStyle 1 - Transparent
Font MS Sans Serif
FontTransparent True
ForeColor &H80000012&
HasDC True
Height 3600
HelpContextID 0
Icon (Icon)
KeyPreview False
Left 0
LinkMode 0 - None
LinkTopic Form1
MaxButton True
MDIChild False
MinButton True
MouseIcon (None)
MousePointer 0 - Default
Moveable True
NegotiateMenus True
OLEDropMode 0 - None
Palette (None)
PaletteMode 0 - Halftone
Picture (None)
RightToLeft False
ScaleHeight 3195
ScaleLeft 0
ScaleMode 1 - Twip
ScaleTop 0
ScaleWidth 4680
ShowInTaskbar True
StartUpPosition 3 - Windows Default
Tag
Top 0
Visible True
WhatsThisButton False
WhatsThisHelp False
Width 4800
WindowState 0 - Normal
(The screen shows the list’s beginning. To see the whole list, use the list’s scroll arrows.)
That list says the caption is normally “Form1”.
To change the caption, click the word “Caption” in that list, then type what you want the caption to be, so the property list’s Caption line becomes this:
Caption Fun stuff
Try that now! It makes the top of Form1 immediately say “Fun stuff”. To see the top of Form1 easily, run the program (by pressing F5) or close the subroutine’s window (by clicking its X button).
Colors
Normally, the inside of the Form1 window shows black characters on a gray background. Get wilder!
Property-list method Here’s how to make the background color be more exciting than gray:
In the property list, click BackColor then BackColor’s down-arrow then “Palette”.
You see 48 background colors. Click the one you want; for your first experiment, try yellow.
Here’s how to make the characters have a color more exciting than black:
In the property list, click ForeColor then ForeColor’s down arrow then “Palette”.
You see 48 foreground colors. Click the one your want; for your first experiment, try red.
Equation method This subroutine makes the background color be yellow, then print (in red letters) “My love for you is as hot as fire”, then print (underneath in blue letters) “but I feel blue”:
Private Sub Form_Load()
BackColor = vbYellow
ForeColor = vbRed
Print "My love for you is as hot as fire"
ForeColor = vbBlue
Print "but I feel blue"
End Sub
In the equations, you can use 8 simple colors: vbYellow, vbRed, vbBlue, vbGreen, vbBlack, vbWhite, vbCyan (which is a greenish blue), and vbMagenta (which is a purplish red).
To invent a fancier color, tell the computer how much Red, Green, and Blue light to mix together; that’s called an RGB mix. In the mix, the Red, Green, and Blue can each be up to 255. For example, you can create orange by shining a red light at full intensity (255) and a green light at lower intensity (127), and keeping the blue light off (0), so orange is RGB(255, 127, 0). This line create orange characters:
ForeColor = RGB(255, 127, 0)
Here are some popular colors and their RGB codes:
Color RGB code
red RGB(255, 0, 0)
green RGB(0, 255, 0)
blue RGB(0, 0, 255)
black RGB(0, 0, 0)
white RGB(255, 255, 255)
gray (between black&white) RGB(127,127, 127)
pink (between red&white) RGB(255,127, 127)
dark red RGB(127, 0, 0)
dark green RGB(0, 127, 0)
dark blue RGB(0, 0, 127)
cyan (greenish blue) RGB(0, 255, 255)
magenta (purplish red) RGB(255, 0, 255)
yellow RGB(255, 255, 0)
orange (betw. red&yellow) RGB(255, 127, 0)
brown (dark orange) RGB(127, 63, 0)
Fonts
Normally, the inside of the Form1 window shows characters whose font is plain (MS Sans Serif) and small: just 8 points high.
(A point is 1/72 of an inch, on paper or on a 14-inch monitor’s screen. If your monitor is slightly bigger than 14-inch, everything on the monitor’s screen looks slightly magnified.)
Try wilder fonts! Here’s how.…
Property-list method In the property list, click Font then Font’s down-arrow.
You see an alphabetical list of fonts. (To see the whole list, use its scroll arrows.) Click the font you want.
Warning: if you pick a font that other computers don’t have, your program might not run well on other computers. Here are the safest fonts to choose:
This font is Times New Roman.
This font is Arial.
This is Courier New.
You see a list of font styles (Regular, Italic, Bold, and Bold Italic). Click the font style you want.
You see a list of recommended sizes. For MS Sans Serif, the recommended sizes are 8, 10, 12, 14, 18, and 24; for the best fonts (Arial, Courier New, and Times New Roman), the recommended sizes are 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, and 72. Click one of those sizes.
If you wish, choose Strikeout or Underline (by clicking their boxes to put check marks there).
When you finish, press ENTER.
Equation method This subroutine prints (in normal letters) “My love for you is” then prints (underneath dramatically) “huge!”
Private Sub Form_Load()
Print "My love for you is"
Font = "Times New Roman"
FontSize = 72
FontBold = True
FontItalic = True
FontUnderline = True
Print "huge"
End Sub
If you want strikeout, you must say:
Font.Strikethrough = True
Notice you must say Strikethrough (not Strikeout) and must put a period before it. (That’s because the folks who invented Visual Basic 6 were accidentally inconsistent. They screwed up!)
Maximize
The Form1 window is normally medium-sized. To maximize it, you can use 3 methods.
Manual method While the program is running (because you pressed F5), you can manually click the Form1 window’s maximize button. That maximizes the window but just temporarily: when you finish running the program (by clicking the Form1 window’s X button), the computer forgets about maximization. The next time you run the program, it will not be maximized, unless you click the maximize button again.
Equation method Insert this equation in Form1’s subroutine:
WindowState = vbMaximized
To make the equation work fast, put it at the subroutine’s beginning (just below the Private Sub line).
Since the code number for “maximized” is 2, you can write the equation more briefly, like this:
WindowState = 2
Property-list method In the property list, click WindowState. Then either type 2 or do this: click WindowState’s down-arrow then “2 — Maximized”.
That makes the property list’s WindowState line become this:
WindowState 2 - Maximized
(You temporarily see just part of “2 — Maximized”; you’ll see the rest when you click elsewhere on the screen.)
Refuse to maximize
Instead of maximizing the Form1 window, you can do just the opposite: you can prevent the user from maximizing. Here’s how.…
In the property list, click MaxButton. Then type an F (or click MaxButton’s down-arrow then “False”). That makes the property list’s MaxButton line become:
MaxButton False
That make Form1’s maximize button be grayed out while the program runs; the maximize button will become gray instead of black. That grayed-out button will ignore all attempts to be clicked, so the window will refuse to maximize.
Adjust form size
Here’s how to adjust Form1’s size.…
Property-list method In the property list, click Width. Then type a number indicating how wide you want Form1, measured in twips. (A twip is a twentieth of a point.)
The normal width is 4800 twips. If you want Form1 to be wider, type a number bigger than 4800 (such as 9000). If you want Form1 to be smaller, type a number smaller than 4800 (such as 2000).
The biggest permissible width is 15360, which makes Form1 stretch all the way across the screen. The smallest permissible width is 1680, which makes Form1 be just slightly over an inch wide.
In the property list, click Height then type how many twips tall you want Form1.
The normal height is 3600 twips. The biggest permissible height is 11520, which makes Form1 be as tall as the screen; but you should stay below 11000, to avoid bumping into the taskbar (which stretches across the screen’s bottom, from the Start button to the clock). The smallest permissible height is 405, which makes Form1 be just tall enough to hold its caption without any other text.
Drag method While the program is running, you can change Form1’s size by dragging its bottom right corner. That changes the size just temporarily: when you finish running the program (by clicking Form1’s X button), the computer forgets how you dragged Form1’s corner, and Form1 reverts to its previous size.
Here’s how to change Form1’s size so the computer remembers the new size:
Make sure the program is not running. (If it’s running, stop it by clicking its X button.)
If you see the subroutine window (which begins by saying Private Sub), close it (by clicking its X button), so you see Form1 (which was hiding behind that subroutine window).
At Form1’s bottom right corner, you see a black square (called a handle). Drag that handle until Form1 becomes the size you wish. That changes Form1’s size permanently (or until you change the size again).
If you want to see the subroutine window again, double-click in the middle of Form1.
Form position
Here’s how to adjust Form1’s position.…
Property-list method In the property list, click StartUpPosition then StartUpPosition’s down-arrow. You see a list of choices.
The computer assumes you want “3 — Windows Default”, which lets the computer use its own best judgment about where to put Form1 on the screen; the computer tends to put Form1 very close to the screen’s top left corner. If you wish, choose “2 — CenterScreen” instead, which will make Form1 be centered on the screen. Or if you wish, choose “0 — Manual” instead and then do this:
In the property list, click Top. How big a gap do you want between Form1’s top and the screen’s top? Type a number indicating the gap’s size (measured in twips).
In the property list, click Left. How big a gap do you want between Form1’s left edge and the screen’s left edge? Type a number indicating the gap’s size (measured in twips).
Afterwards, whenever you run the program (by pressing F5), Form1 will be positioned as you requested.
Drag method While the program is running, you can move Form1 by dragging its title bar (the blue horizontal bar that’s at Form1’s top and typically says “Form1”). That moves Form1 just temporarily; when you finish running the program (by clicking Form1’s X button), the computer forgets how you dragged Form1, and Form1 reverts to its previous position.
Here’s how to drag Form1 so the computer remembers how you dragged:
Make sure the program is not running. (If it’s running, stop it by clicking its X button.)
At the screen’s bottom right corner, you should see the Form Layout window. (If you accidentally erased it, make it appear by clicking “View” then “Form Layout Window”.)
The Form Layout window shows a mock-up of a monitor, with Form1 in that monitor’s blue screen.
On that blue screen, drag Form1 slightly, until the mock-up correctly shows where you want Form1 positioned on the screen (and which corner you want Form1 to be near).
Afterwards, whenever you run the program (by pressing F5), Form1 will be positioned as you requested.
Objects
You’ve learned how to create and manipulate an object called “Form1”. You can create other kinds of objects also! Here’s how.…
Command button
Try this experiment. Exit from VB (by clicking its X button). Then go back into VB by doing this:
Click “Start” then “Programs” then “Microsoft Visual Studio 6.0” (if you see that choice) then “Microsoft Visual Basic 6.0”. Press ENTER (which has the same effect as double-clicking “Standard EXE”).
Click “AutoRedraw”. Press the T key (to make AutoRedraw be True).
You see the Form1 window (which is blank). At the screen’s left edge, you should see this Toolbox:
Pointer Picture Box
Label Text Box
Frame Command Button
Check Box Option Button
Combo Box List Box
Horizontal Scroll Bar Vertical Scroll Bar
Timer Drive List Box
Directory List Box File List Box
Shape Line
Image Data
OLE
(If you accidentally erased it, make it reappear by clicking “View” then “Toolbox”.)
Each object in that Toolbox is called a tool. Double-click the Command Button tool. That makes a command button appear in the middle of Form1. The button is a rectangle and says “Command1” on it.
(If you wish, you can drag that button to a different place in Form1. You can also change the button’s size by dragging its 9 square handles. But for your first experiment, you just leave the command button where the computer put it.)
The command button says “Command1” on it. Just for fun, let’s make it say “Please click me” instead. To do that, click Caption (in the property list) and type “Please click me”, so the property list’s Caption line becomes:
Caption Please click me
That makes the command button’s caption become “Please click me”.
Notice that the property list concerns the command button and its caption (instead of Form1’s caption), because the command button is highlighted.
Let’s write a program so if a human clicks the command button (which says “Please click me”), Form1 will say “Thanks for the click”. To do that, double-click the command button. The double-clicking tells the computer you want to write a subroutine about that object (the command button).
The computer starts writing the subroutine for you. The computer writes:
Private Sub Command1_Click()
End Sub
Insert this line in the middle of the subroutine —
Print "Thanks for the click"
so the subroutine looks like this:
Private Sub Command1_Click()
Print "Thanks for the click"
End Sub
That subroutine tells the computer that when the Command1 button is clicked, the computer should print “Thanks for the click” onto Form1. (The computer knows it should print that onto Form1 rather than onto the command button, because the Print command applies just to forms, not to buttons.)
Then run the program (by pressing F5). You’ll see Form1 with a button on it that says “Please click me”. If you click the button, the subroutine makes Form1 say “Thanks for the click”. If you click the button again, the subroutine makes Form1 say “Thanks for the click” again, so Form1 says “Thanks for the click” twice, like this:
Thanks for the click
Thanks for the click
Click the button as often as you wish; each time, Form1 says “Thanks for the click” again. If you click the button many times, Form1 will eventually get filled up and won’t be able to show any more thanks. If that happens, make Form1 bigger temporarily, by clicking its maximize button, so you can see more thanks.
When you get tired of clicking, end the program by clicking Form1’s X button.
Two buttons Let’s write a program that has two command buttons! Let’s make the first button be called “Red” and the second button be called “Blue”. If the human clicks the “Red” button, let’s make Form1 turn red; if the human clicks the “Blue” button, let’s make Form1 turn blue.
To do all that, start a new program as follows:
Close any old program.
If you’re already in VB, click “File” then “New Project” (then handle any questions about saving your old program). If you’re not in VB yet, click “Start” then “Programs” then “Microsoft Visual Studio 6.0” (if you see that choice) then “Microsoft Visual Basic 6.0” then press ENTER.
Press ENTER (which has the same effect as double-clicking “Standard EXE.”).
Click “AutoRedraw”. Press the T key (to make AutoRedraw be True).
You see the Form1 window (which is blank).
In the Toolbox, double-click the Command Button tool. A command button appears in Form1 and is called Command1. In the property list, click Caption then type “Click here for red”, so the property list’s Caption line becomes:
Caption Click here for red
That makes the command button’s caption become “Click here for red”.
In the Toolbox, double-click the Command Button tool again. That makes another command button appear in Form1 and be called Command2. Unfortunately, the Command2 button covers up the Command1 button, so you can’t see the Command1 button. Drag the Command2 button out of the way (toward the right), so you can see both buttons side-by-side.
The Command2 button should be highlighted. (If it’s not highlighted, click it to make it highlighted.) In its property list, change its Caption from “Command2” to “Click here for blue”.
Now your screen shows Form1 with two buttons on it. The first button says “Click here for red”. The second button says “Click here for blue”.
Double-click the “Click here for red” button, and write this subroutine for it:
Private Sub Command1_Click()
BackColor = vbRed
End Sub
That subroutine says: clicking that button will make Form1’s background color be red.
Move that subroutine out of the way (by clicking its X button), so you can see Form1.
Double-click the “Click here for blue” button, and write this subroutine for it:
Private Sub Command2_Click()
BackColor = vbBlue
End Sub
While you’re writing that subroutine, you’ll see the other subroutine above it.
Then run the program by pressing F5. Here’s what happens.…
You see Form1 with two buttons on it. The first button says “Click here for red”; if you click it, Form1 turns red. The other button says “Click here for blue”; if you click it, Form1 turns blue.
Try clicking one button, then the other. Click as often as you like. When you get tired of clicking, end the program (by clicking Form1’s X button).
Where to put command buttons A good habit is to put command buttons side-by-side, in Form1’s bottom right corner. That way, the buttons won’t interfere with the Print command or any other objects on Form1.
Exit button To stop running a typical program, you have to click its X button. Some humans don’t know to do that. To help them, create a command button called “Exit”, so that clicking it will make the computer exit from the program.
To do that, create an ordinary command button; but make the button’s caption say “Exit” (or anything else you prefer, such as “Quit” or “End” or “Abort” or “Click here to end the program”), and make the button’s subroutine say End, like this:
Private Sub Command3_Click()
End
End Sub
Put that Exit button in Form1’s bottom right corner.
Option button
You learned how to use the Command Button tool. The Option Button tool is similar. Here are the differences.…
A command button is a gray rectangle, with a caption inside the rectangle. An option button is a tiny white circle, with a caption to the right of the circle.
Although you can put command buttons and option buttons wherever you wish, it’s customary to arrange command buttons horizontally (so the second command button is to the right of the first) but arrange option buttons vertically (so the second option button is below the first). The option buttons (and their captions) form a vertical list of choices. Command buttons are best if you have just 1, 2, or 3 choices; option buttons are best if you have 4, 5, or 6 choices.
When the human starts running your program, the first option button (which is Option1) has a black dot inside the white circle, and the computer automatically does Option1’s subroutine (even if the human hasn’t clicked the Option1 button yet).
Afterwards, if the human clicks a different option button, the black dot moves to that option button and the computer does that button’s subroutine. At any given moment, just one of the option buttons contains the black dot.
If you’re annoyed that Option1 starts with a black dot inside it (and automatically gets its subroutine run), make Option1’s caption say “Nothing” or “Plain” or “Regular” and have no subroutine.
OK button When the human clicks an option button, the computer can react to the click immediately, but that might startle and upset the human. If you want to be gentler, delay the computer’s reaction until the human also clicks an OK button, which confirms the human’s desires.
To do that, make the option buttons have no subroutines, so nothing will happen when those buttons are clicked. In Form1’s bottom right corner, create a command button whose caption says “OK” and whose subroutine looks like this:
Private Sub Command1_Click()
If Option1.Value Then write here what to do if Option1 button clicked
If Option2.Value Then write here what to do if Option2 button clicked
If Option3.Value Then write here what to do if Option3 button clicked
End Sub
That subroutine says: when the OK button is clicked, notice which option button was clicked and react appropriately.
Here’s how to start typing that subroutine. Type the word “If”, then a space, then the word “Option”, then 1, then a period. After you’ve typed the period, the computer will show you a list of what can come after the period. From that list, choose “Value” by using one of these methods.…
Method 1: scroll down to the word “Value” (by using the list’s scroll arrow), then double-click “Value”.
Method 2: highlight the word “Value” (by pressing the V key), then press the TAB key (which confirms that you want the highlighted choice).
Then type the rest of the subroutine.
Put the OK button in Form1’s bottom right corner.
Check box
A check box is a small white square, with a caption to the right of the square. At first, the white square has nothing inside it: the square is empty. While the program is running, clicking the square makes a check mark (a) appear in the square. If you click it again, the check mark goes away.
To create a check box, double-click the Check Box tool. A check box appears in the middle of Form1. Drag the check box wherever you wish. The first check box’s caption is temporarily “Check1”; to change that caption, click Caption (in the property list) and type whatever caption you wish.
If you want the computer to react immediately to whether the check box is checked, give the check box this subroutine:
Private Sub Check1_Click()
If Check1.Value = vbChecked Then
write here what to do if Check1 box just became checked
Else
write here what to do if Check1 box just became unchecked
End If
End Sub
For example, this subroutine makes the computer print “I am dressed” if the check box is just became checked, but print “I am naked” if the check box just became empty:
Private Sub Check1_Click()
If Check1.Value = vbChecked Then
Print "I am dressed"
Else
Print "I am naked"
End If
End Sub
When that program runs, the check box starts by being empty. Clicking the check box makes you see a and makes the computer print “I am dressed”. The next time you click the check box, the a disappears from the box, so the box becomes empty and the computer prints “I am naked”. Clicking the check box again makes the a reappear and makes the computer print “I am dressed”.
Form1 can contain many check boxes. The human can check several at the same time, so that several of the boxes contain check marks simultaneously. That’s how check boxes differ from option buttons: the human can check several check boxes but must choose just one option button.
Like option buttons, check boxes are usually arranged vertically (so the second check box is below the first).
OK button If Form1 contains several check boxes, you should typically delay the computer’s reaction until the human has decided which boxes to check, has checked all the ones desired, and has clicked an OK button to confirm that the correct boxes are checked.
To do that, make the boxes have no subroutines. Instead, create an OK button in Form1’s bottom right corner (by creating a command button there and making its caption be “OK”), then make the OK button’s subroutine look like this:
Private Sub Command1_Click()
If Check1.Value = vbChecked Then
write here what to do if Check1 box is checked
Else
write here what to do if Check1 box is unchecked
End If
If Check2.Value = vbChecked Then
write here what to do if Check2 box is checked
Else
write here what to do if Check2 box is unchecked
End If
End Sub
That subroutine says: when the OK button is clicked, notice which check boxes are checked and react appropriately.
For example, let’s make the computer print “I love you” in whatever style the human chooses: “bold” or “italic” or “bold italic” or “regular” (neither bold nor italic). To do that, create a check box for “bold”, a check box for “italic”, and an OK button that looks at which boxes are checked and prints “I love you” in the desired style. Here’s how to do all that:
Create a check box (called Check1) with caption “Bold”.
Create a check box (called Check2) with caption “Italic”.
Create a command button (called Command1) with caption “OK” and this subroutine:
Private Sub Command1_Click()
If Check1.Value = vbChecked Then
FontBold = True
Else
FontBold = False
End If
If Check2.Value = vbChecked Then
FontItalic = True
Else
FontItalic = False
End If
Print "I love you"
End Sub
Label
A label is a sneaky command button. Here’s the best way to create one:
Click the Label tool (just once). On Form1, drag from where you want the label’s top left corner to where you want the label’s bottom right corner.
Here’s how a label differs from a command button.…
A command button is a rectangle that’s small, and you can clearly see its four sides. A label is a rectangle that you typically make bigger, and its four sides are invisible while the program is running.
A command button’s caption is short, centered in the button’s middle. A label’s caption is typically longer: if you make the label big, you can make the caption be quite long, containing many words. In a typical label, the caption is a whole paragraph.
If your paragraph doesn’t fit in your label, enlarge the label by dragging the label’s handles. Another way to make your paragraph fit in your label is to do this before typing the paragraph:
In the property list, click AutoSize, then AutoSize’s down-arrow, then True. That lets the label automatically widen to fit the paragraph.
If the paragraph is too long to fit on a single line, also do this before typing the paragraph: click WordWrap, then WordWrap’s down-arrow, then True. That lets the label automatically grow taller to fit the paragraph. (To make that procedure work, do it before typing the paragraph and make sure you’ve set AutoSize to True.)
Printing to a label The Print command makes the computer start printing at Form1’s top left corner. If you want to print elsewhere on Form1, create Label1 where you want to print, then tell the computer to “print to Label1”. To “print to Label1”, tell the computer to “print to Label1’s caption”.
For example, suppose you want to print the answer to 4 + 2.
This Form1 subroutine prints the answer (which is 6) at Form1’s top left corner:
Private Sub Form_Load()
Print 4 + 2
End Sub
This Form1 subroutine prints the answer at Label1’s caption instead:
Private Sub Form_Load()
Label1.Caption = 4 + 2
End Sub
When writing that subroutine, make sure you say Label1.Caption, not just Caption. (If you accidentally say just Caption, that Form1 subroutine will print at Form1’s caption instead of Label1’s caption.)
That subroutine, if typed correctly, makes Label1’s caption say “6” instead of “Label1”, so you see 6 at Label1’s top left corner.
List box
A list box is a big white box that contains a list of choices, such as these color choices —
Red
Green
Blue
or these style choices —
Bold
Italic
or these country choices —
United States
Canada
Mexico
The list can be short (2 or 3 choices) or long (hundreds of choices). If the list is too long to fit in the box, the computer will automatically add scroll arrows so humans can scroll through the list.
To create a list box, double-click the List Box tool. A list box (big white box) appears in the middle of Form1. Drag the list box wherever you wish.
The first list box is called List1. Inside that list box, you temporarily see the word “List1”, but you should put your own list of choices there instead. Here’s how:
In the property list (at the screen’s right side), click List then List’s down-arrow. Type the first item you want in the list (such as “United States”); at the end of that typing, tap the ENTER key while holding down the Ctrl key. Type the second item you want in the list (such as “Canada”); at the end of that typing, press Ctrl with ENTER again. Type the third item you want in the list (such as “Mexico”). Continue that process, until you’ve typed all the items you want. (You can type as many items as you wish; as you type, the items automatically scroll up to let you type more.) At the end of the last item, press just ENTER (without holding down the Ctrl key).
On Form1, you see the list box containing some of your choices. Probably your choices are too many or too long-winded to fit in the box completely. Enlarge the box by dragging its handles, until the box becomes wide enough to hold the widest choice and tall enough to hold all or many of the choices. (If the box isn’t tall enough, the computer automatically adds scroll arrows so humans can scroll through the list while the program runs.)
SingleSelect You can give List1 this kind of subroutine:
Private Sub List1_Click()
Select Case List1.Text
Case "United States"
write here what to do if “United States” clicked
Case "Canada"
write here what to do if “Canada” clicked
Case "Mexico"
write here what to do if “Mexico” clicked
End Select
End Sub
If you want the action to be delayed until the human clicks an OK button, do this:
Create the OK button (a command button whose caption is “OK”).
Give List1 no subroutine, but give the OK button this kind of subroutine:
Private Sub Command1_Click()
Select Case List1.Text
Case "United States"
write here what to do if “United States” clicked
Case "Canada"
write here what to do if “Canada” clicked
Case "Mexico"
write here what to do if “Mexico” clicked
End Select
End Sub
MultiSelect If you want to let the human select several items from the list (instead of just one item), do this:
In List1’s property list, click MultiSelect then MultiSelect’s down-arrow.
Click either “1 — Simple” or “2 — Extended”. (If you choose “1 — Simple”, the human can select several items by clicking them, and deselect an item by clicking that item again. If you choose “2 — Extended”, the human can select one item by clicking it, select or deselect extra items by holding down the Ctrl key while clicking them, and select a contiguous bunch of items easily by clicking the bunch’s first item and SHIFT-clicking the last.)
Create an OK button (a command button whose caption is “OK”).
Give List1 no subroutine, but give the OK button this kind of subroutine:
Private Sub Command1_Click()
If List1.Selected(0) Then write here what to do if the list’s top item (“United States”) clicked
If List1.Selected(1) Then write here what to do if the list’s next item (“Canada”) clicked
If List1.Selected(2) Then write here what to do if the list’s next item (“Mexico”) clicked
End Sub
Label Next to your list box, you should put a message, explaining the list box’s purpose to the human.
To put the message there, you could use Print statements, but it’s hard to get Print statements to print in exactly the right spot (next to the list box). Here’s an easier way to put your message in the right spot: create a label (sneaky command button) whose caption is your message. Drag the label until it’s next to your list box. Give the label no subroutine, so clicking the label makes no difference.
Text box
You already learned that Form1’s subroutine can contain this line:
x = InputBox("What is your name?")
When you run the program, that line makes the computer create an input box. The input box is a pop-up window containing a message (“What is your name?”), a wide white box (in which the human types a response), and an OK button (which the human clicks when finished typing).
That technique works adequately but gives you no control: you have no control over the size or position of the window, the message, the white response box, or the OK button.
To be more professional, get control by creating a text box instead. Here’s how.
Double-click the Text Box tool. That creates a text box (a white box in which the human can type a response). Drag it wherever you wish. Adjust its size by dragging its handles.
The box’s interior temporarily says “Text1”. Make the box’s interior be blank instead, by doing this: in the property list, click Text then press the SPACE bar then the BACKSPACE key.
Above the box (or left of the box), create a label (sneaky command button) containing a message (such as “What is your name?”)
Below the box (or right of the box), create an OK button (a command button whose caption is “OK”). Make the OK button’s subroutine include this line —
x = Text1.Text
and anything else you want the computer to do, such as:
Print "I adore anyone whose name is "; x
Form1 can contain several text boxes. For example, you can include:
a text box for the human’s first name
a text box for the human’s last name
a text box for the human’s address
text boxes for the human’s city, state, and ZIP code
That makes Form1 be truly a form to fill in! Create just one OK button to handle all those text boxes, so the human clicks the OK button after filling in the entire form.
Password character If you want the human to type a password into a text box, do this: in the text box’s property list, click PasswordChar then type an asterisk (the symbol *). That makes the box show asterisks instead of the characters the human is typing. That prevents enemies from discovering the password by peeking over the human’s shoulder.
MultiLine Normally the text box is restricted to holding just one line of text. To let the text box handle several lines of text well, do this:
In Text1’s property list, click MultiLine then press the T key (which stands for True). That lets the text box handle several lines of text, lets the human press the ENTER key at the end of each line, and lets the computer press the ENTER key automatically if there are too many words to fit on a line.
Make the text box taller and wider (by dragging its handles), so it can show more lines of text and more words per line. That reduces the human’s frustration.
In Text1’s property list, click ScrollBars then the ScrollBars down-arrow then “2 - Vertical”. That creates a vertical scroll bar, which helps the human move through the text, in case you didn’t make the text box tall enough to handle all the words.
Combo box
A combo box is a fancy text box that includes a list of suggested responses.
To create a combo box, double-click the Combo Box tool. That creates a combo box. Like a text box, it’s a white box in which the human can type a response; but the combo box’s right edge shows a down-arrow, which the human can click to see a list of suggested responses.
Drag the combo box wherever you wish.
The box’s interior temporarily says “Combo1”. Make the box’s interior be blank instead, by doing this: in the property list, click Text then press the SPACE bar then the BACKSPACE key.
In the property list, click List then List’s down-arrow. Type your list of suggested responses; at the end of each suggested response, press Ctrl with ENTER, except that end the end of the final suggested response press just ENTER.
Make the combo box wide enough to hold the longest response (by dragging the combo box’s right handle).
Above (or left of) the combo box, create a label (sneaky command button) containing a prompt (an instruction to the human about what to put into the box).
Below (or right of) the combo box, create an OK button (a command button whose caption is “OK”). Make the OK button’s subroutine include this line —
x = Combo1.Text
and anything else you want the computer to do, such as:
Print "I'm glad you said "; x
3 kinds of combo boxes In Combo1’s property list, click Style then Style’s down-arrow. You see 3 styles:
0 - Dropdown Combo
1 - Simple Combo
2 - Dropdown List
Click whichever style you wish. If you don’t choose otherwise, the computer assumes you want “0 — Dropdown Combo”. That works as I described: the human can type anything into the box, and the suggestion list appear just if the human clicks the box’s down-arrow.
If you choose “1 — Simple Combo” instead, the human can still type anything into the box, and the suggestion list always appears (without requiring a down-arrow click) if you make the combo icon tall enough to hold the list.
If you choose “2 — Dropdown List” instead, the human cannot type into the box; the human is required to choose from the suggestion list, which appears when the human clicks the down-arrow. If the human tries typing a character (such as a letter of the alphabet or a digit) instead of clicking the down-arrow, the computer peeks in the suggestion list and chooses the first item beginning with that character.
Line
You can become an artistic programmer! For example, here’s how to draw a line on Form1.
Click the Line tool (just once). On Form1, drag from where you want the line’s beginning to where you want the line’s end. You can make the line be horizontal, vertical, or diagonal. The line is black.
Change the color Here’s how to make the line be more interesting than black. In the property list, click BorderColor then BorderColor’s down-arrow then Palette. You see 48 colors; click your favorite.
Shape
Here’s how to draw a rectangle on Form1.
Click the Shape tool (just once). On Form1, drag from where you want the rectangle’s top left corner to where you want the rectangle’s bottom right corner. The rectangle appears.
The rectangle itself consists of 4 black lines. The rectangle’s inside is gray (unless you changed Form1’s background color).
Change the colors Here’s how to make the rectangle’s 4 lines be more interesting than black:
In the property list, click BorderColor then BorderColor’s down-arrow then Palette. You see 48 colors; click your favorite.
Here’s how to make the rectangle’s inside be more interesting than gray:
In the property list, click FillStyle then FillStyle’s down-arrow then “0 - Solid”. That temporarily makes the rectangle’s inside be black. In the property list, then click FillColor then FillColor’s down-arrow then Palette. You see 48 colors; click whichever color you want for the rectangle’s inside.
Change the shape Here’s how to turn the rectangle into a different shape.
In the property list, click Shape then Shape’s down-arrow. You see this list of shapes:
0 - Rectangle
1 - Square
2 - Oval
3 - Circle
4 - Rounded Rectangle
5 - Rounded Square
From that list, click whichever shape you want.
If you click Rectangle, the rectangle will stay the way it was.
If you click one of the other choices, the rectangle will shrink just enough so it becomes a “perfect square” or an “oval” or a “perfect circle” or a “rectangle with rounded corners” or a “square with rounded corners”. That new shape will be centered at the same point where the original rectangle was centered.
Frame
A frame is a sophisticated rectangle. To create one, click the Frame tool (just once). On Form1, drag from where you want the frame’s top left corner to where you want the frame’s bottom right corner. The frame appears.
Here’s how the frame differs from a normal rectangle.…
In a normal rectangle, the 4 lines are black. In a frame, the 4 lines are created with a special effect that makes the lines look chiseled into your screen.
A normal rectangle has no caption. A frame does have a caption, which appears near the frame’s top left corner. For your first frame, which is called Frame1, the caption starts by saying “Frame1”. Here’s how to change the caption: in the property list, click Caption then type whatever words you want in the caption.
A frame protects its contents from outside influences. Here are two examples:
A frame’s inside is gray, even if Form1’s background is a different color.
If you create an option button in a frame (not by double-clicking the Option Button tool, but rather by clicking the Option Button tool just once and then dragging diagonally within the frame), and then you create more option buttons in the frame that way, those buttons are protected from the buttons that are outside the frame: an option button outside the frame can have a dot in it, and an option button inside the frame can have a dot in it at the same time. When your program starts running, none of the option buttons in the frame has a dot yet, until you click one of those buttons.
Horizontal scroll bar
The traditional way to let the human input a number is to create an InputBox or Text box. Here’s an alternative that’s more fun.…
Double-click the Horizontal Scroll Bar tool. A horizontal scroll bar appears in the middle of Form1. You can drag it wherever you wish and adjust its size (by dragging its handles). To see it better, I recommend that you widen it (by dragging its handles), so it’s always as wide as Form1.
The horizontal scroll bar consists of a left-arrow (which is on the left), a right-arrow (which is on the right), and a little square between them. The little square is called a slider. When you run the program (by pressing F5), the slider will blink, to encourage the human to slide it (by dragging it). The human can slide it to the right and back again to the left.
Go ahead: try it now! Create a horizontal scroll bar, run the program, and have fun sliding the slider!
Subroutine The horizontal scroll bar is called HScroll1. For your first experiment, give it this subroutine:
Private Sub HScroll1_Change()
Print HScroll1.Value
End Sub
The computer has already typed the top and bottom lines, so type just the middle line. That subroutine says: whenever the human moves the slider (changes its position by dragging), print the slider’s value. (The value is 0 if the slider is at the far left, 32767 if the slider at the far right.)
Try it! Run the program, slide the slider, and see the computer print a number showing where you slid to.
Extreme positions If you don’t want the slider’s far-right position to be called “32767”, click Max (in HScroll1’s property list) and type a smaller number instead (such as 100). Try that now: make it 100!
If you don’t want the slider’s far-left position to be called “0”, click Min (in HScroll1’s property list) and type a different number instead (such as -100).
The Max and Min numbers must no bigger than 32767, no more negative than -32768, and have no decimal points.
Starting position The human can move the slider. Before the human moves the slider, the slider starts at position 0 (which is at the far left, unless you changed Min).
If you want the slider to start at a different position, click Value then type the number of where you want the slider to start (such as 50).
Arrows The slider is surrounded by a left-arrow and a right-arrow. The human can nudge the slider slightly to the left by clicking the left arrow, and slightly to the right by clicking the right-arrow. Clicking those arrows nudges the slider just slightly (1 position).
If you want those arrows to produce bigger nudges, click SmallChange (in the property list) and type a number bigger than 1. For example, type 10.
White rectangles The slider is also surrounded by white rectangles. The human can nudge the slider to the left by clicking the left white rectangle, and to the right by clicking the right white rectangle. Clicking those rectangles nudges the slider just slightly (1 position).
If you want those rectangles to produce bigger nudges, click LargeChange (in the property list) and type a number bigger than 1. It’s customary to make that number be bigger than SmallChange; for example, make Large Change be 50.
Variables Instead of saying Print HScroll1.Value, you can say:
x = HScroll1.Value
That makes x become whatever number the slider’s position is. Afterwards, you can say Print x or, better yet, if you’ve created a Label, say:
Label1.Caption = x
Vertical scroll bar
The Vertical Scroll Bar tool resembles the Horizontal Scroll Bar tool but produces a scroll bar that’s vertical. Here are the details.…
Double click the Vertical Scroll Bar tool. A vertical scroll bar appears in the middle of Form1. It consists of an up-arrow (which is at the top), a down-arrow (which is at the bottom), and a slider (little square) between them. When you run the program, the human can slide the blinking slider down and back up again.
Subroutine The vertical scroll bar is called VScroll1. For your first experiment, give it this subroutine:
Private Sub VScroll1_Change()
Print VScroll1.Value
End Sub
That subroutine says: whenever the human moves the slider (changes its position by dragging), print the slider’s value. (The value is 0 if the slider is at the top, 32767 if the slider is at the bottom.)
Extreme positions If you don’t want the slider’s top position to be called “0”, click Min (in VScroll1’s property list) and type a different number instead (such as 100). If you don’t want the slider’s bottom position to be called “32767”, click Max (in VScroll1’s property list) and type a different number instead (such as 0).
Arrows, white rectangles, and variables A vertical scroll bar handles these features in a fashion similar to a horizontal scroll bar.
Timer
Let’s make the computer print “I love you” repeatedly, so Form1 begins like this:
I love you
I love you
I love you
I love you
I love you
etc.
To make the computer repeat easily, use the Timer tool. Double-click it. A timer icon (which looks like a stopwatch) appears on Form1. (If that timer icon covers another icon, drag the timer icon out of the way.)
Subroutine Double-click the timer icon, then write a subroutine saying what activity to repeat, like this:
Private Sub Timer1_Timer()
Print "I love you"
End Sub
The computer has already typed the top and bottom lines, so type just the middle line.
Frequency interval Tell the computer how frequently to repeat that activity. To do that, click Interval (in Timer1’s property list) then type how many milliseconds the computer should wait before doing or repeating the activity. (A millisecond is a thousandth of a second.)
For example, if you want the computer to wait 1 second before printing the next “I love you”, type 1000 (since 1 second is 1000 milliseconds). If you want the computer to wait 2 seconds before printing the next “I love you”, type 2000. If you want the computer to wait just half a second before printing the next “I love you”, type 500.
You can type any number from 1 to 65535. If you type 1, the interval is 1 millisecond. If you type 65535, the interval is 65535 milliseconds, which is 65.535 seconds, which is slightly more than a minute.
Technical note:
The computer will obey your interval just approximately, since the computer examines its clock once every jiffy (which is 55 milliseconds), not every millisecond. The interval that the computer produces will be slightly different from what you requested: the error can be up to 55 milliseconds.
For your first experiment, type 1000, so the computer waits 1 second before printing the next “I love you”.
Run the program (by pressing F5). The computer will wait 1 second, then print “I love you”, then wait 1 more second, then print another “I love you” underneath, then wait 1 more second, then print another “I love you” underneath, etc.
If you want the computer to wait a shorter interval (so each “I love you” comes faster), change the interval to less than 1000.
Run When you run the program (by pressing F5), the computer waits (for 1000 milliseconds or however long you said), then does the timer’s subroutine (which prints “I love you”), then pauses again, then prints again, the pauses again, then prints again, etc.
While the program is running, the timer icon does not appear on Form1: the timer icon is invisible. The timer icon is visible just while you’re designing the program, not while you’re running it.
Disable Let’s make the computer say —
I love you
then pause for 3 seconds, then give the joke’s punch line:
except for your hair
Here’s how.…
Start a new program. Make Form1’s subroutine say:
Print "I love you"
Create a timer icon. Give it an Interval of 3000, and make its subroutine say:
Print "except for your hair"
When you run that program, the computer will say “I love you”, then pause for 3 seconds, then say “except for your hair”. After another 3-second pause, it will say “except for your hair” again. It will keep saying “except for your hair” again and again, separated by 3-second pauses.
If you want the computer to say “except for your hair” just once, change the timer icon’s subroutine to this:
Print "except for your hair"
Timer1.Enabled = False
That makes the computer print “except for your hair” (after a 3-second interval) then disable the timer (so the timer gets turned off and doesn’t print any more).
Add Form
Besides Form1, you can create extra forms, called Form2, Form3, Form4, etc. To create an extra form, click the Add Form button (which is near the screen’s top, under the words “Edit” and “View”), then double-click the Form icon. To make that form act normally, click AutoRedraw then press the T key (which stands for True).
For example, let’s make a command button (on Form1) so that when you click that button, Form2 suddenly appears and says “I love you”. Here’s how.…
Start a new program (so you have a Form1).
Create a command button (by double-clicking the Command Button tool). Give it the caption “Click me for a surprise” (by typing “Click me for a surprise”). Double-click the button and type this subroutine line:
Form2.Visible = True
That means: when the button is clicked, make Form2 suddenly become visible.
Create Form2 normally, by doing this: click the Add Form button, double-click the Form icon, click AutoRedraw, then press the T key.
Make Form2 say “I love you”, by double-clicking in Form2 then typing this subroutine line:
Print "I love you"
When you run the program (by pressing F5), you see Form1, which contains a command button captioned “Click me for a surprise”. If you click that button, the computer displays Form2, which covers Form1 and says “I love you”.
To stop running the program, close the Form2 window (by clicking its X button) then close the Form1 window (by clicking its X button).
Menu
You can create a menu.
Menu bar
At the top of Form1, let’s create this menu bar:
Love Hate
Let’s program the computer so clicking “Love” makes the computer print “I love you”, and clicking “Hate” makes the computer print “I hate you because you’re a human”.
Here’s how to accomplish all that.…
Create the menu bar Click the Menu Editor tool (which is near the screen’s top, under the word “Project”). Type the menu’s first word (“Love”), press the TAB key, type “mnu” and that word again (“mnuLove”), and press ENTER. Do the same for the second word: type “Hate” then press TAB then type “mnuHate”. If you did that correctly, you see this list of menu items:
Love
Hate
Click OK.
At the top of Form1, you see the menu bar you created:
Love Hate
Congratulations! You created a menu!
Create menu subroutines Click “Love”, then write this subroutine telling the computer what to do if “Love” is clicked:
Private Sub mnuLove_Click()
Print "I love you"
End Sub
(The computer already typed the top and bottom lines for you, so type just the middle line.) When you finish typing that line, click the subroutine window’s X button.
Click “Hate”, then write this subroutine about clicking “Hate”:
Private Sub mnuHate_Click()
Print "I hate you because you're a human"
End Sub
Then click the subroutine window’s X button.
Run the program Go ahead: run the program (by pressing the F5 key). You see the menu bar you created:
Love Hate
Clicking “Love” makes the computer print “I love you”; clicking “Hate” makes the computer print “I hate you because you’re a human”.
Pull-down menu
Let’s expand the menu by adding “Color”, so the menu becomes this:
Love Hate Color
Let’s program the computer so clicking “Color” makes this pull-down menu appear under Color:
Yellow
Red
Let’s program so clicking one of those colors makes Form1’s background be that color.
Here’s how to accomplish all that.…
Create a new menu item If your program is still running, stop it (by clicking its X button). Close any subroutine window (by clicking its X button).
You see Form1.
Click the Menu Editor tool again. You see this list of menu items:
Love
Hate
Add “Color” to that list. Here’s how: click under “Hate”, then click in the Caption box, then type “Color”. Press the TAB key, then type “mnuColor”, then press ENTER. If you did that correctly, you see this list of menu items:
Love
Hate
Color
Create a pull-down menu To create Color’s pull-down menu (saying “Yellow”, “Green”, and “Red”), make that list become:
Love
Hate
Color
····Yellow
····Red
Here’s how. Click “Æ” (which makes the computer create an indented list). Click in the Caption box, type “Yellow”, press TAB, type “mnuYellow”, then press ENTER. Do the same for “Red”: type “Red”, press TAB, then type “mnuRed”. If you did that correctly, you see:
Love
Hate
Color
····Yellow
····Red
Click OK.
Create menu subroutines At the top of Form1, you see the menu bar you created:
Love Hate Color
Click “Color”. You see Color’s pull-down menu:
Yellow
Red
Click “Yellow”, then write this subroutine about Yellow:
Private Sub mnuYellow_Click()
BackColor = vbYellow
End Sub
Then click the subroutine window’s X button.
Click “Color” then “Red”, then write this subroutine about Red:
Private Sub mnuRed_Click()
BackColor = vbRed
End Sub
Then click the subroutine window’s X button.
Run the program Go ahead: run the program (by pressing the F5 key). You see the menu bar you created:
Love Hate Color
Clicking “Color” makes the computer show Color’s pull-down menu; clicking the “Yellow” or “Red” makes Form1’s background turn that color.
Submenu
Let’s expand Color’s pull-down menu by adding “Gray”, so the menu becomes this:
Yellow
Red
Gray
Let’s program the computer so clicking “Gray” makes this submenu appear to the right of Gray:
Light Gray
Dark Gray
Let’s program so clicking one of those shades of gray (“Light Gray” or “Dark Gray”) makes Form1’s background be that color.
Here’s how to accomplish all that.…
Create a new menu item If your program is still running, stop it (by clicking its X button). Close any subroutine window (by clicking its X button).
You see Form1.
Click the Menu Editor tool again. You see this list of menu items:
Love
Hate
Color
····Yellow
····Red
Add “Gray” to that list. Here’s how: click under “Red”, then click “Æ”, then click in the Caption box, then type “Gray”. Press the TAB key, then type “mnuGray”, then press ENTER. If you did that correctly, you see this list of menu items:
Love
Hate
Color
····Yellow
····Red
····Gray
Create a submenu To create Gray’s submenu (saying “Light Gray” and “Dark Gray”), make that list become:
Love
Hate
Color
····Yellow
····Red
····Gray
········Light Gray
········Dark Gray
Here’s how. Click “Æ” (which makes the computer indent farther). Click in the Caption box, type “Light Gray”, press TAB, type “mnuLightGray” (without any space before “Gray”), then press ENTER. Do the same for “Dark Gray”: type “Dark Gray”, press TAB, then type “mnuDarkGray” (without any spaces). If you did that correctly, you see:
Love
Hate
Color
····Yellow
····Red
····Gray
········Light Gray
········Dark Gray
Click OK.
Create menu subroutines At the top of Form1, you see the menu bar you created:
Love Hate Color
Click “Color”. You see Color’s pull-down menu:
Yellow
Red
Gray 8
Next to “Gray”, the symbol “8” means Gray has a submenu. Click “Gray”; you see this submenu:
Light Gray
Dark Gray
Click “Light Gray”, then write this subroutine about it:
Private Sub mnuLightGray_Click()
BackColor = RGB(191, 191, 191)
End Sub
Then click the subroutine window’s X button.
Click “Color” then “Gray” then “Dark Gray”, then write this subroutine about it:
Private Sub mnuDarkGray_Click()
BackColor = RGB(63, 63, 63)
End Sub
Then click the subroutine window’s X button.
Run the program Go ahead: run the program (by pressing the F5 key). You see the menu bar you created:
Love Hate Color
Clicking “Color” makes the computer show Color’s pull-down menu; clicking “Gray” makes the computer show Gray’s submenu; then clicking “Light Gray” or “Dark Gray” makes Form1’s background turn that color.
Rearranging menu items
After you’ve created a menu, here’s how to rearrange its items.…
Click the Menu Editor tool again. You see a list of menu items, like this:
Love
Hate
Color
····Yellow
····Red
····Gray
········Light Gray
········Dark Gray
To change one of those items, click it (so it’s highlighted in a blue band), then do one of these actions (using the buttons above the item):
If you click the right-arrow button, the item becomes more indented.
If you click the left-arrow button, the item becomes less indented.
If you click the up-arrow button, the item swaps positions with the item above.
If you click the down-arrow button, the item swaps positions with the item below.
If you click the Delete button, the item disappears.
If you click the Insert button, a blank line is inserted above the item & highlighted.
If you click the Next button, the blue highlight moves down to the next line.
To change the item’s word,
type the word into the Caption box (and type its mnu into the Name box).
You can create a 6-level menu:
If you leave an item unindented, it will appear on the menu toolbar.
If you indent an item, it will appear in a pull-down menu.
If you double-indent an item, it will appear in a submenu.
If you triple-indent an item, it will appear in a sub-submenu.
If you quadruple-indent an item, it will appear in a sub-sub-submenu.
If you quintuple-indent an item, it will appear in a sub-sub-sub-submenu.
That’s as far as Microsoft lets you go!
Underlined letters
To be sophisticated, make the computer underline the first letter of each menu item, so when you run the program the menu toolbar looks like this —
Love Hate Color
and Color’s pull-down menu looks like this —
Yellow
Red
Gray 8
and Gray’s pull-down menu looks like this:
Light Gray
Dark Gray
Here’s how to do all that: in the list of menu items, make each item begin with an ampersand (the symbol “&”), like this:
&Love
&Hate
&Color
····&Yellow
····&Red
····&Gray
········&Light Gray
········&Dark Gray
Do that by adding an ampersand into the Caption box (but not the Name box). For example, the first item’s Caption box should say &Love (but that item’s Name box should say just mnuLove, without an ampersand).
After you’ve done all that (so the letters are underlined), you can do this trick while the program runs:
Instead of clicking “Love”, you can tap the Alt key then the L key.
Instead of clicking “Hate”, you can tap the Alt key then the H key.
Instead of clicking “Color” then “Yellow”, you can tap Alt then C then Y.
Instead of clicking “Color” then “Red”, you can tap Alt then C then R.
Instead of clicking “Color” then Gray” then “Light Gray”,
you can tap Alt then C then G then L.
Instead of clicking “Color” then “Gray” then “Dark Gray”,
you can tap Alt then C then G then D.
Instead of tapping the Alt key, you can tap the F10 key, which does the same thing.
That whole method works just if, in each menu, all items begin with different letters. If two items in a menu begin with the same letter, rename one of the items or else underline a different letter. (To underline a different letter, put the ampersand before that letter. For example, to underline the v in “Love”, to produce “Love”, say “Lo&ve”.)
Keyboard shortcuts
In that program, choosing “Dark Gray” is tedious: you must click “Color” then “Gray” then “Dark Gray” (or tap Alt then C then G then D). Here’s how to create a keyboard shortcut, so that pressing Ctrl with D will choose “Dark Gray”.
Click the Menu Editor tool, so you see the list of menu items:
&Love
&Hate
&Color
····&Yellow
····&Red
····&Gray
········&Light Gray
········&Dark Gray
Click “&Dark Gray” then the Shortcut box’s down-arrow then “Ctrl+D”. That makes Ctrl+D be the shortcut for “Dark Gray”. While the program is running, you can choose “Dark Gray” by doing this (instead of choosing “Color” then “Gray” then “Dark Gray”): while holding down the Ctrl key, just tap the D key.
To teach humans that you made Ctrl+D be the shortcut for “Dark Gray”, the computer automatically writes “Ctrl+D” next to “Dark Gray” in the menu, so the Gray menu looks like this:
Light Gray
Dark Gray Ctrl+D
Using that same method, you can make Ctrl+L be the shortcut for “Light Gray”: in the list of menu items, click “&Light Gray” then the Shortcut box’s down-arrow then “Ctrl+L”. Then the Gray menu look like this:
Light Gray Ctrl+L
Dark Gray Ctrl+D
Pretty output
Here are VB’s nifty features. Enjoy!
Plotting
On Form1, the top left corner is called position (0, 0). If you start at the top
left corner and go 1000 twips to the right and then 2000 twips down, you get to
position (1000, 2000).
In a subroutine, you can say:
Line (0, 0)-(1000, 2000)
That draws a diagonal line from position (0, 0) to position (1000, 2000). The line is black and thin. Try it!
Here’s a list of plotting commands you can give:
Command What the computer will draw
Line (0, 0)-(1000, 2000) black straight line from (0, 0) to (1000, 2000)
Line (0, 0)-(1000, 2000), vbRed red straight line from (0, 0) to (1000, 2000)
Line (0, 0)-(1000, 2000), vbRed, B red box with corners at (0, 0) and (1000, 2000)
Line (0, 0)-(1000, 2000), vbRed, BF filled-in red box, cornered at (0, 0) and (1000, 2000)
PSet (1000, 2000) tiny black dot at (1000, 2000)
PSet (1000, 2000), vbRed tiny red dot at (1000, 2000)
Circle (1000, 2000), 500 black circle centered at (1000, 2000), radius 500
Circle (1000, 2000), 500, vbRed red circle centered at (1000, 2000), radius 500
Besides vbRed, you can use other simple colors (vbYellow, vbBlue, vbGreen, vbBlack, vbWhite, vbCyan (which is a greenish blue), vbMagenta (which is a purplish red), or an RGB mix such as RGB(255, 127, 0), as explained on page 476, column 2.
Clear screen
In a subroutine, you can say:
Cls
That stands for “Clear screen”. It makes the computer erase everything that was written on Form1 by Print, Line, PSet, or Circle. (It does not erase Form1’s buttons or other objects.)
For example, suppose you create a command button whose subroutine says:
Cls
Print "love"
Clicking that command button will make Form1 say just “love” and erase all of Form1’s previous writings.
Tab
In a subroutine, you can say:
Print Tab(6); "hot"
That makes the computer indent to the 6th print position then print “hot”, like this:
JJJJJhot
Here’s a fancier example:
Print Tab(6); "hot"; Tab(13); "buns"
That makes the computer indent to the 6th print position, then print “hot”, then skip to the 13th print position, then print “buns”, like this:
JJJJJhotJJJJbuns
How wide is a print position? That depends on what font you’re using. If you’re using Courier New, where each character has the same width, a print position is the width of one character. If you’re using MS Serif or Times New Roman or Ariel, the letter “W” is wider than “i”; a print position is defined to be “the width of the average character”, which in most fonts is the width of “J”.
Tab without a number If you say Tab without a number, the computer will do Tab(15) or Tab(15 + 14) or Tab(15 + 14 + 14) or Tab(15 + 14 + 14 + 14) or something similar.
For example, saying —
Print Tab; "hot"
is the same as saying:
Print Tab(14); "hot"
It prints:
JJJJJJJJJJJJJhot
Saying —
Print Tab; "hot"; Tab; "buns"
is the same as saying:
Print Tab(15); "hot"; Tab(15 + 14); "buns"
It prints:
JJJJJJJJJJJJJJhotJJJJJJJJJJJbuns
Saying —
Print Tab; "I love to eat hot"; Tab; "buns"
makes the computer skip to print position 15, then print “I love to eat hot”, then skip to print position 15 + 14 + 14 (since print position 15 + 14 has already been passed), then print “buns”, like this:
JJJJJJJJJJJJJJI love to eat hotJJJJJJJJJJJbuns
Comma Instead of saying Tab without a number, you can type just a comma (and omit the semicolons next to it). So instead of saying —
Print Tab; "hot"; Tab; "buns"
you can say:
Print , "hot", "buns"
These lines print a list of words and their opposites:
Print "good", "bad"
Print "black", "white"
Print "grandparent", "grandchild"
Print "he", "she"
Each of those lines contains a comma, which makes the computer skip to the 15th print position, so the computer prints this table:
good bad
black white
grandparent grandchild
he she
Format a number
This program makes an ugly number look prettier:
Print FormatNumber(27931.6)
The FormatNumber(27931.6) means “format the number 27931.6 so it looks like money”; it’s the string “27,931.60”. Notice that the computer inserts a comma (because the number is at least 1000) and puts 2 digits after the decimal point. The computer prints:
27,931.60
The computer prints just that. It does not put a blank space before or after the number.
Here’s another example:
Print FormatNumber(8.739)
The computer will round 8.739, to put just 2 digits after the decimal point and produce the string “8.74”. The computer will print:
8.74
Here’s how to make the computer print a million dollars:
Print FormatNumber(1000000)
The computer will print:
1,000,000.00
Problem: if you add $1.49 and $1.01, what’s the total? The answer is supposed to be $2.50. If you say —
Print 1.49 + 1.01
The computer will print 2.5, which doesn’t look like money. If you say —
Print FormatNumber(1.49 + 1.01)
the computer will print:
2.50
How many digits? After the decimal point, how many digits do you want? The computer assumes you want 2 digits, unless you say otherwise.
For example, if you say —
Print FormatNumber(91.9814276, 5)
the computer will put 5 digits after the decimal point and print:
91.98143
If you say —
Print FormatNumber(91.9814276, 0)
the computer will put no digits after the decimal point. It will print just:
92
Percent Instead of saying FormatNumber, you can say FormatPercent, which converts the number to a percent. To do so, FormatPercent multiplies the number by 100, then does FormatNumber tricks on it (to make the number look pretty and have 2 digits after the decimal point), then writes a percent sign.
For example, suppose you say:
Print FormatPercent(.75)
The computer starts with .75 and converts it to a percent. To do that the computer multiplies .75 by 100 (to get 75), then makes the number look pretty (75.00), then writes a percent sign; so the computer prints:
75.00%
If you say —
Print FormatPercent(0.51639)
the computer will print:
51.64%
If you say —
Print FormatPercent(0.51639, 0)
the computer will print no digits after the decimal point; it will print just:
52%
Other countries I’ve been describing how FormatNumber and FormatPercent work in the United States. In other countries, it works differently, to adjust to how those countries handle money and other numbers.
To find out what country and language your computer is assuming, click Start then Settings then Control Panel, then double-click Regional Settings, then click Number for further details.
If you’re sharing the computer with colleagues, do not change those Regional Settings unless you get their permission!
Loops
Here’s how to make the computer repeat.
Do…Loop
The computer can be religious. Just make Form1’s subroutine say this:
MsgBox "I worship your feet"
MsgBox "But please wash them"
When you run the program, the computer shows a message box saying “I worship your feet” and waits for the human to click OK. Then the computer shows a message box saying “But please wash them” (and waits for the human to click OK again).
To make the computer do the lines many times, say “Do” above the lines and say “Loop” below them, so the subroutine looks like this:
Do
MsgBox "I worship your feet"
MsgBox "But please wash them"
Loop
Notice the lines being repeated (the MsgBox lines) should be between the words Do and Loop and indented. (To indent a line, press the TAB key at the line’s beginning. To unindent a line, click the line’s beginning then press the BACKSPACE key.)
Run the program (by pressing the F5 key). The computer says “I worship your feet” (and waits for the human to click OK), then says “But please wash them” (and waits for OK), then goes back and says “I worship your feet” again (and waits for OK), then says “But please wash them” again (and waits for OK), then goes back and says the same stuff again, and again, and again, and again, forever.
Since the computer’s thinking keeps circling back to the same lines, the computer is said to be in a loop. In that subroutine, the Do means “do what’s underneath and indented”; the Loop means “loop back and do it again”. The lines that say Do and Loop — and the lines between them — form a loop, which is called a Do loop.
The computer does that loop repeatedly, forever — or until you
abort the program by doing
this: while holding down the Ctrl key, tap the PAUSE/BREAK key,
which is the last key in the top row. That makes the computer stop running your
program; it will break out
of your program; it will
abort your program.
Then click the End button
(which is a blue square near the screen’s top, just under the words “Tools” and
“Add-Ins”).
In that program, since the computer tries to go round and round the loop forever, the loop is called infinite. The only way to stop an infinite loop is to abort it.
Warning: the PAUSE/BREAK key does not work with .exe files. If a program contains an infinite loop, do not turn it into an .exe file. If you make the mistake of turning this program into an .exe file (by choosing “Make .exe” from the File menu), you’ll have created a nasty program that refuses to stop and even refuses to let the typical computer “Shut Down”: it won’t stop until you turn the computer’s power off.
GoTo
Instead of typing —
Do x
MsgBox "I worship your feet"
MsgBox "But please wash them"
Loop
you can type:
joe: MsgBox "I worship your feet"
MsgBox "But please wash them"
GoTo joe
The top line (named joe) makes the computer say “I worship your feet”. The next line makes the computer say “But please wash them”. The bottom line makes the computer Go back To the line named joe, so the computer forms a loop. The computer will loop forever — or until you press Ctrl with PAUSE/BREAK.
You can give a line a short name (such as joe) or a long name (such as BeginningOfMyFavoriteLoop). Put the name at the beginning of the line. After the name, put a colon (the symbol “:”).
The line’s name (such as joe or BeginningOfMyFavorite Loop) is called the line’s label.
Skip ahead Did you ever dream about having a picnic in the woods? These lines express that dream:
Print "Let's munch"
Print "sandwiches under"
Print "the trees!"
They make the computer print:
Let's munch
sandwiches under
the trees!
Let’s turn that dream into a nightmare where we all become giant termites. To do that, insert the shaded items:
Print "Let's munch"
GoTo conclusion
Print "sandwiches under"
conclusion: Print "the trees!"
The computer begins by printing “Let’s munch”. Then the computer does GoTo conclusion, which makes the computer Go skip down To the conclusion line, which prints “the trees!”. So the program makes the computer print just this:
Let's munch
the trees!
Is GoTo too powerful? Saying GoTo gives you great power: if you make the computer GoTo an earlier line, you’ll create a loop; if you make the computer GoTo a later line, the computer will skip over several lines of your program.
Since saying GoTo is so powerful, programmers are afraid to say it. Programmers know that the slightest error in saying GoTo will make a program act very bizarre! Programmers feel more comfortable using milder words instead (such as Do…Loop), which are safer and rarely get botched up. since saying GoTo is scary, many computer teachers prohibit students from using it, and many companies fire programmers who say GoTo instead of Do…Loop.
But saying GoTo is fine when you’ve learned how to control the power! Though I’ll usually say Do…Loop instead of GoTo, I’ll say GoTo in certain situations where saying Do…Loop would be awkward.
Exiting a Do loop
Let’s create a guessing game, where the human tries to guess the computer’s favorite color, which is pink. To do that, say GoTo or Exit Do or Loop Until. Here’s how.…
GoTo Just makeForm1’s subroutine say this:
AskTheHuman: guess = InputBox("What's my favorite color?")
If guess = "pink" Then
Print "Congratulations! You discovered my favorite color."
Else
MsgBox "No, that's not my favorite color. Try again!"
GoTo AskTheHuman
End If
The top line (which is called AskTheHuman) asks the human to guess the computer’s favorite color.
If the guess is “pink”, the computer prints:
Congratulations! You discovered my favorite color.
But if the guess is not pink, the computer will instead say “No, that’s not my favorite color” and then Go back To AskTheHuman again to guess the computer’s favorite color.
Exit Do Here’s how to write that subroutine without saying GoTo:
Do
guess = InputBox("What's my favorite color?")
If guess = "pink" Then Exit Do
MsgBox "No, that's not my favorite color. Try again!"
Loop
Print "Congratulations! You discovered my favorite color."
The Do loop makes the computer do this repeatedly: ask “What’s my favorite color?” and then say “No, that’s not my favorite color.”
The only way to stop the loop is to guess “pink”, which makes the computer Exit from the Do loop; then the computer proceeds to the line underneath the Do loop. That line prints:
Congratulations! You discovered my favorite color.
Loop Until Here’s another way to program the guessing game:
Do
MsgBox "You haven't guessed my favorite color yet!"
guess = InputBox("What's my favorite color?")
Loop Until guess = "pink"
Print "Congratulations! You discovered my favorite color."
The Do loop makes the computer do this repeatedly: say “You haven’t guessed my favorite color yet!” and then ask “What’s my favorite color?”
The Loop line makes the computer repeat the indented lines again and again, until the guess is “pink”. When the guess is “pink”, the computer proceeds to the line underneath the Loop and prints “Congratulations!”
The Loop Until’s condition (guess = “pink”) is called the loop’s goal. The computer does the loop repeatedly, until the loop’s goal is achieved. Here’s how:
The computer does the indented lines, then checks whether the goal is achieved yet. If the goal is not achieved yet, the computer does the indented lines again, then checks again whether the goal is achieved. The computer does the loop again and again, until the goal is achieved. Then the computer, proud at achieving the goal, does the program’s finale, which consists of any lines under the Loop Until line.
Saying —
Loop Until guess = "pink"
is just a briefer way of saying this pair of lines:
If guess = "pink" Then Exit Do
Loop
For…Next
Let’s make the computer print every number from 1 to 12, like this:
1
2
3
4
5
6
7
8
9
10
11
12
To do that, put these lines into Form1’s subroutine:
For x = 1 To 12
Print x
Next
The top line (For x = 1 To 12) says that x will be every number from 1 to 12; so x will be 1, then 2, then 3, etc. The line underneath is indented (by pressing the TAB key) and says what to do about each x: it says to Print each x.
Whenever you write a subroutine that contains the word For, you must say Next; so the bottom line says Next.
The indented line, which is between the For line and the Next line, is the line that the computer will do repeatedly; so the computer will repeatedly Print x. The first time the computer prints x, the x will be 1, so the computer will print:
1
The next time the computer prints x, the x will be 2, so the computer will print:
2
The computer will print every number from 1 up to 12.
When men meet women Let’s make the computer print these lyrics:
I saw 2 men
meet 2 women.
Tra-la-la!
I saw 3 men
meet 3 women.
Tra-la-la!
I saw 4 men
meet 4 women.
Tra-la-la!
They all had a party!
Ha-ha-ha!
To do that, type these lines —
The first line of each verse: Print "I saw"; x; "men"
The second line of each verse: Print "meet"; x; "women."
The third line of each verse: Print "Tra-la-la!"
Blank line under each verse: Print
and make x be every number from 2 up to 4:
For x = 2 To 4
Print "I saw"; x; "men"
Print "meet"; x; "women."
Print "Tra-la-la!"
Next
At the end of the song, print the closing couplet:
For x = 2 To 4
Print "I saw"; x; "men"
Print "meet"; x; "women."
Print "Tra-la-la!"
Next
Print "They all had a party!"
Print "Ha-ha-ha!" x
That program makes the computer print the entire song.
Here’s an analysis:
For x = 2 To 4
The computer will do the Print "I saw"; x; "men"
indented lines repeatedly, Print "meet"; x; "women."
for x=2, x=3, and x=4. Print "Tra-la-la!"
Next
Then the computer will Print "They all had a party!"
print this couplet once. Print "Ha-ha-ha!"
Since the computer does the indented lines repeatedly, those lines form a loop. Here’s the general rule: the statements between For and Next form a loop. The computer goes round and round the loop, for x=2, x=3, x=4, and x=5. Altogether, it goes around the loop 4 times, which is a finite number. Therefore, the loop is finite.
If you don’t like the letter x, choose a different letter. For example, you can choose the letter i:
FOR i = 2 TO 4
Print "I saw"; i; "men"
Print "meet"; i; "women."
Print "Tra-la-la!"
Next
Print "They all had a party!"
Print "Ha-ha-ha!"
When using the word For, most programmers prefer the letter i; most programmers say “For i” instead of “For x”. Saying “For i” is an “old tradition”. Following that tradition, the rest of this book says “For i” (instead of “For x”), except in situations where some other letter feels more natural.
Print the squares To find the square of a number, multiply the number by itself. For example, the square of 3 is “3 times 3”, which is 9. The square of 4 is “4 times 4”, which is 16.
Let’s make the computer print the square of 3, 4, 5, etc., up to 10, like this:
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
The square of 8 is 64
The square of 9 is 81
The square of 10 is 100
To do that, type this line —
Print "The square of"; i; "is"; i*i
and make i be every number from 3 up to 10, like this:
For i = 3 To 10
Print "The square of"; i; "is"; i * i
Next
Print the squares as a table Let’s make the computer print the squares more beautifully, to form this table:
Number Square
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
Here’s how:
Print "Number", "Square"
For i = 3 To 10
Print i, i * i
Next
The top line prints the word “Number” at the top of the first column, and the word “Square” at the top of the second. (Those words are called the column headings.) The For line says i goes from 3 to 10; to begin, i is 3. The indented line makes the computer print:
3 9
The bottom line makes the computer do the same thing for the next i, and for the next i, and for the next; so the computer prints the whole table.
Count how many copies This program prints “love” a dozen times:
For i = 1 To 12
Print "love"
Next
Here’s a poem:
I'm having trouble
With my nose.
The only thing it does is:
Blows!
This program prints 4 copies of that poem, onto 4 sheets of paper:
For i = 1 To 4
Printer.Print "I'm having trouble"
Printer.Print "With my nose."
Printer.Print "The only thing it does is:"
Printer.Print "Blows!"
Printer.EndDoc
Next
The Printer.EndDoc makes the printer eject the paper.
Here’s a smarter program, which asks how many copies you want:
n = Val(InputBox("How many copies of the poem do you want?"))
For i = 1 To n
Printer.Print "I'm having trouble"
Printer.Print "With my nose."
Printer.Print "The only thing it does is:"
Printer.Print "Blows!"
Printer.EndDoc
Next
When you run that program, the computer asks:
How many copies of the poem do you want?
If you answer 5 (and click the OK button), the n becomes 5 (so the computer prints 5 copies of the poem). If you answer 7 instead, the computer prints 7 copies. Print as many copies as you like!
That program illustrates this rule:
To make the For...Next loop flexible,
say “For i = 1 To n” and let the human input the n.
Count to midnight This program makes the computer count to midnight:
For i = 1 To 11
Print i
Next
Print "midnight"
The computer will print:
1
2
3
4
5
6
7
8
9
10
11
midnight
Semicolon Let’s put a semicolon at the end of the indented line:
For i = 1 To 11
Print i;
Next
Print "midnight"
The semicolon makes the computer print each item on the same line, like this:
1 2 3 4 5 6 7 8 9 10 11 midnight
If you want the computer to press the ENTER key before “midnight”, insert a Print line:
For i = 1 To 11
Print i;
Next
Print "midnight"
That extra Print line makes the computer press the ENTER key just before “midnight”, so the computer will print “midnight” on a separate line, like this:
1 2 3 4 5 6 7 8 9 10 11
midnight
Nested loops Let’s make the computer count to midnight 3 times, like this:
1 2 3 4 5 6 7 8 9 10 11
midnight
1 2 3 4 5 6 7 8 9 10 11
midnight
1 2 3 4 5 6 7 8 9 10 11
midnight
To do that, put the entire program between the words For and Next:
For j = 1 To 3
For i = 1 To 11
Print i;
Next
Print "midnight"
Next
That version contains a loop inside a loop: the loop that says “For i” is inside the loop that says “For j”. The j loop is called the outer loop; the i loop is called the inner loop. The inner loop’s variable must differ from the outer loop’s. Since we called the inner loop’s variable “i”, the outer loop’s variable must not be called “i”; so I picked the letter j instead.
Programmers often think of the outer loop as a bird’s nest, and the inner loop as an egg inside the nest. So programmers say the inner loop is nested in the outer loop; the inner loop is a nested loop.
Step The For statement can be varied:
Statement Meaning
For i = 5 To 17 Step .1 The i will go from 5 to 17, counting by tenths.
So i will be 5, then 5.1, then 5.2, etc., up to 17.
For i = 5 To 17 Step 3 The i will be every 3rd number from 5 to 17.
So i will be 5, then 8, then 11, then 14, then 17.
For i = 17 To 5 Step -3 The i will be every 3rd number from 17 down to 5.
So i will be 17, then 14, then 11, then 8, then 5.
To count down, you must use the word STEP. To count from 17 down to 5, give this instruction:
For i = 17 To 5 Step -1
This program prints a rocket countdown:
For i = 10 To 1 STEP -1
Print i
Next
Print "Blast off!"
The computer will print:
10
9
8
7
6
5
4
3
2
1
Blast off!
This statement is tricky:
For i = 5 To 16 Step 3
It says to start i at 5, and keep adding 3 until it gets past 16. So i will be 5, then 8, then 11, then 14. The i won’t be 17, since 17 is past 16. The first value of i is 5; the last value is 14.
In the statement For i = 5 To 16 Step 3, the first value or initial value of i is 5, the limit value is 16, and the step size or increment is 3. The i is called the counter or index or loop-control variable. Although the limit value is 16, the last value or terminal value is 14.
Programmers usually say “For i”, instead of “For x”, because the letter i reminds them of the word index.
Fancy calculations
The computer can do fancy calculations.
Exponents
In Form1’s subroutine, try giving this command:
Print 4 ^ 3
To type the symbol ^, do this: while holding down the SHIFT key, tap this key:
^ 6 |
That symbol (^) is called a caret.
In that line, the “4 ^ 3” makes the computer use the number 4, three times.
The computer will multiply together those three 4’s, like this: 4 times 4 times
4. Since
“4 times 4 times 4” is 64, the computer will print 64.
In the expression “4 ^ 3”, the 4 is called the base; the 3 is called the exponent.
Here’s another example:
Print 10 ^ 6
The “10 ^ 6” makes the computer use the number 10, six times.
The computer will multiply together those six 10’s (like this:
10 times 10 times 10 times 10 times 10 times 10) and print the answer, 1000000.
Here’s another example:
Print 3 ^ 2
The “3 ^ 2” makes the computer use the number 3, two times. The
computer will multiply together those two 3’s (like this:
3 times 3) and print the answer, 9.
Order of operations The symbols +, -, *, /, and ^ are all called operations.
To solve a problem, the computer uses the three-step process taught in algebra and the “new math”. For example, suppose you say:
Print 70 - 3 ^ 2 + 8 / 2 * 3
The computer will not begin by subtracting 3 from 70; instead, it will use the three-step process:
The problem is 70 - 3 ^ 2 + 8 / 2 * 3
Step 1: get rid of ^. Now the problem is 70 - 9 + 8 / 2 * 3
Step 2: get rid of * and /. Now the problem is 70 - 9 + 12
Step 3: get rid of + and -. The answer is 73
In each step, it looks from left to right. For example, in step 2, it sees / and gets rid of it before it sees *.
Speed Though exponents are fun, the computer handles them slowly. For example, the computer handles 3 ^ 2 slower than 3 * 3. So for fast calculations, say 3 * 3 instead of 3 ^ 2.
Square roots What positive number, when multiplied by itself, gives 9? The answer is 3, because 3 times itself is 9.
3 squared is 9. 3 is called the square root of 9.
To make the computer deduce the square root of 9, type this:
Print Sqr(9)
The computer will print 3.
When you tell the computer to Print Sqr(9), make sure you put the parentheses around the 9.
The symbol Sqr is called a function. The number in parentheses (9) is called the function’s input (or argument or parameter). The answer, which is 3, is called the function’s output (or value).
Sqr(9) gives the same answer as 9 ^ .5. The computer handles Sqr(9) faster than 9 ^ .5.
Cube roots What number, when multiplied by itself and then multiplied by itself again, gives 64? The answer is 4, because 4 times 4 times 4 is 64. The answer (4) is called the cube root of 64.
Here’s how to make the computer find the cube root of 64:
Print 64 ^ (1 / 3)
The computer will print 4.
Stripping
Sometimes the computer prints too much info: you wish the computer would print less, to save yourself the agony of reading excess info irrelevant to your needs. Whenever the computer prints too much info about a numerical answer, use Abs, Fix, Int, Round, or Sgn.
Abs removes any minus sign. For example, the Abs of -3.89 is 3.89. So if you say Print Abs(-3.89), the computer will print just 3.89.
Fix removes any digits after the decimal point. For example, the Fix of 3.89 is 3. So if you say Print Fix(3.89), the computer will print just 3. The Fix of -3.89 is -3.
Int rounds the number DOWN to an integer that’s LOWER. For example, the Int of 3.89 is 3 (because 3 is an integer that’s lower than 3.89); the Int of -3.89 is -4 (because -4 is lower than -3.89).
Round can round to the NEAREST integer. For example, the Round of 3.89 is 4. So if you say Print Round(3.89), the computer will print 4. The Round of -3.89 is -4. If you say Print Round(865.739, 2), the computer will round 865.739 to 2 decimal places and print 865.74.
Sgn removes ALL the digits and replaces them with a 1 — unless the number is 0. For example, the Sgn of 3.89 is 1. The Sgn of -3.89 is -1. The Sgn of 0 is just 0.
Abs, Fix, Int, Round, and Sgn are all called stripping functions or strippers or diet functions or diet pills, because they strip away the number’s excess fat and reveal just the fundamentals that interest you.
Types of data
Here’s how to make your program consume less RAM and run faster: before you use a variable (such as x), tell the computer what type of data the x will stand for, by giving one of these 11 commands:
Command Meaning RAM for x
Dim x As Byte x will be a number from 0 to 255, without a decimal point and without a negative sign 1 byte
Dim x As Integer x will be a number from 0 to 32767, with maybe a negative sign in front, but without a decimal point 2 bytes
Dim x As Long x will be a number from 0 to 2147483647, with maybe a negative sign in front, but without a decimal point 4 bytes
Dim x As Currency x will be a number from 0 to 922337203685477.5807, with just 4 digits after decimal point, and maybe a negative sign 8 bytes
Dim x As Single x will be a number from 0 to 3E38 , with maybe a negative sign and decimal point; I’m satisfied with 7-digit accuracy 4 bytes
Dim x As Double x will be a number from 0 to 1E308, with maybe a negative sign and decimal point; I’m satisfied with 15-digit accuracy 8 bytes
Dim x As Boolean x will be either the word True or the word False 2 bytes
Dim x As Date x will be a date and time (such as #12/31/2005 11:59:30 PM#), with a year between 100 and 9999 8 bytes
Dim x As Object x will be an object (such as Form1 or Command1) 4 bytes
Dim x As String x will be a string (such as “I love you”), maybe up to 2 billion characters long 1 byte per character (plus 10 bytes if length not specified)
Dim x As Variant I don’t know what x will be “16 bytes” if number, “1 byte per character, plus 22 bytes” if not number
For example, suppose you want x to be 52. Before saying
“x = 52”, tell the computer what type of data the x will be. Since x will be a
number between 0 and 255, say “Dim x As Byte”, so your subroutine looks like
this:
Dim x As Byte
x = 52
According to the chart’s top line, saying “Dim x As Byte” lets x consume just 1 byte of RAM. The computer can store 52 (or any whole number up to 255) in just 1 byte of RAM, because the computer stores the number by using a special trick called binary representation.
If you neglect to say “Dim x As Byte”, the computer doesn’t know what type of data the x will stand for, so the computer makes x be a Variant variable, which can hold anything but consumes more RAM: at least 16 bytes. Saying “Dim x As Byte” lets the program consume less RAM and run faster, since the computer can handle shorter data faster.
Details
Here are more details about those 11 commands.…
Byte A Byte is a number from 0 to 255, without a decimal point. Here’s an example:
Dim x As Byte
x = 52
Print x
The first line says x is a Byte. The next line says x is 52. The bottom line makes the computer print:
52
A Byte cannot have a decimal point. For example, if you try to say —
Dim x As Byte
x = 52.9
Print x
the computer will round 52.9 to 53, so x will be 53, and the computer will print:
53
A Byte cannot be bigger than 255. If you say “Dim x As Byte” and then try to say “x = 256”, the computer will gripe by saying this when you run the program:
Run-time error '6':
Overflow
The computer will give that same gripe if you try to say “x = -1”, since a Byte cannot be a negative number.
Integer An Integer is a number from 0 to 32767, with maybe a negative sign in front, but without a decimal point. For example, these numbers can all be Integer:
0 1 2 3 10 52 53 1000 32767
-1 -2 -3 -10 -52 -53 1000 -32767
Technical note: although 32768 is slightly too big to be an Integer, -32768 is a special number that can be an Integer, though it’s rarely used.
If you say “Dim x As Integer” and then try to say “x = 52.9”, the computer will round 52.9 to 53, so x will be 53.
Long A Long is a number from 0 to 2147483647, with maybe a negative sign in front, but without a decimal point. For example, these numbers can all be Longs:
0 1 2 3 10 52 53 1000 1000000 2147483647
0 -1 -2 -3 -10 -52 -53 -1000 -1000000 -2147483647
Technical note: although 2147483648 is slightly too big to be a Long, -2147483648 is a special number that can be a Long, though it’s rarely used.
If you say “Dim x As Long” and then try to say “x = 52.9”, the computer will round 52.9 to 53, so x will be 53.
Currency A Currency is a number from 0 to 922337203685477.5807, with at most 4 digits after the decimal point, and maybe with a negative sign. For example, these numbers can all be Currency:
0 1 2 3 4.75 4.95 4.99 4.9995 922337203685477.5807
0 -1 -2 -3 -4.75 -4.95 -4.99 -4.9995 -922337203685477.5807
Technical note: although 922337203685477.5808 is slightly too big to be a Currency, -922337203685477.5808 is a special number that can be a Currency, though it’s rarely used.
If you say “Dim x As Currency” and then try to say “x = 8.14529”, the computer will make x be 8.1453.
You can use Currency to handle dollars-and-cents variables (such as Price or HourlyWage or Profit), other variables that needs a decimal point followed by 1, 2, 3, or 4 digits, and other variable that needs to handle numbers in the trillions.
Single A Single is a number from 0 to 3E38 (which is a “3 followed by 38 zeros”, which is 300000000000000000000000000000000000000), with maybe a negative sign and a decimal point. After the decimal point, you can have as many digits as you wish. For example, these numbers can all be Single:
0 1 2 3 4.99 4.9995 4.999527 1000.236 26127.85 3E38
0 -1 -2 -3 -4.99 -4.9995 -4.999527 -1000.236 -26127.85 -3E38
The computer manages to store a Single rather briefly (just 4 bytes) by “cheating”: the computer stores the number just approximately, to an accuracy of about 7 significant digits.
For example, if you say —
Dim x As Single
x = 100 / 3
Print x
the computer will print 7 digits:
33.33333
If you say —
Dim x As Single
x = 1000.2369
Print x
the computer will round to 7 digits and print:
1000.237
When handling Single variables, the computer can give inaccurate results. The inaccuracy is especially noticeable if you do a subtraction where the two numbers nearly equal each other. For example, if you say —
Dim x As Single
Dim y As Single
x = 8000.1
y = x - 8000
Print y
the computer will make x be approximately 8000.1, so y will be approximately .1. The Print line will print:
0.1000977
Notice that the last few digits are wrong! That’s the drawback of Single: you can’t trust the last few digits of the answer! Single is accurate enough for most scientists, engineers, and statisticians, since they realize all measurements of the real world are just approximations; but Single is not good enough for accountants, who fret over every penny. Single’s errors drive accountants bananas. For accounting problems that involve decimals, use Currency instead of Single, since Currency is always accurate, though slower.
Technical notes:
A Single can be slightly bigger than 3E38. The biggest permissible Single is actually 3.402823E38.
If a Single is at least a million (which is 10000000 and is 1E7), the computer will print it by using E notation.
If a Single is a decimal tinier than .1 and has lots of digits after the decimal point, the computer will print it by using E notation.
If a Single is a decimal tinier than 2E-45 (which is .000000000000000000000000000000000000000000002), the computer might handle it very inaccurately or even just call it 0.
Double A Double is similar to a Single but can include more digits, since the computer uses 8 bytes for it instead of 4 bytes. It’s more accurate than a Single but still can make tiny errors (unlike Currency, which is always correct but limited to 4 digits after the decimal point). Here are the details about Double.…
A Double is a number from 0 to 1E308, with maybe a negative sign and a decimal point. After the decimal point, you can have as many digits as you wish. The computer stores the number just approximately, to an accuracy of about 15 significant digits.
For example, if you say —
Dim x As Double
x = 100 / 3
Print x
the computer will print 15 digits:
33.3333333333333
If you say —
Dim x As Double
Dim y As Double
x = 8000.1
y = x - 8000
Print y
the computer will make x be approximately 8000.1, so y will be approximately .1. The Print line will print:
0.100000000000364
Notice that the last few digits are wrong. In this example about subtracting 8000 from 8000.1, the answer produced by Double is slightly wrong but closer to the truth than the answer produced by Single. If you insist on a completely correct answer, say Currency instead.
Technical notes:
A Double can be slightly bigger than 1E308. The biggest permissible Double is actually 1.79769313486232E308.
If a Double is at least a quadrillion (which is 1000000000000000 and is 1E15), the computer will print it by using E notation.
If a Double is a decimal tinier than .1 and has lots of digits after the decimal point, the computer will print it by using E notation.
If a Double is a decimal tinier than 5E-324, the computer might handle it very inaccurately or even just call it 0.
Boolean A Boolean is either the word True or the word False. Here’s an example:
Dim x As Boolean
x = True
Print x
The computer will print:
True
Here’s another example:
Dim x As Boolean
x = False
Print x
The computer will print:
False
Technical notes:
If you say “Dim x As Boolean” and then try to say “x = 0”, the computer will make x be False.
If you say “Dim x As Boolean” and then say “x = 1” (or say that x is any other non-zero number), the computer will make x be True.
Date A Date is a date with time. For example, these lines make x be December 31, 2005, at 30 seconds after 11:59 PM:
Dim x As Date
x = #12/31/2005 11:59:30 PM#
Print x
Notice you must put the symbol # before and after the date-with-time. The computer will print:
12/31/2005 11:59:30 PM
For the year, you can pick 2005 or 1999 or 1776 or 1492 or even earlier. You can pick any year from 100 (which was shortly after Christ) to 9999 (which is many centuries from now). If you type a 2-digit year, the computer will put “20” before your typing, to make a 4-digit year (unless your 2-digit year is at least 30, in which case the computer will put “19” before your typing instead).
You can omit any part of the date-and-time that doesn’t interest you. For example, if you don’t care about the seconds, leave them out. If you don’t care about the time-of-day, leave it out and type just the date; if you don’t care about the date, leave it out and type just the time of day.
The computer makes assumptions:
If you leave out the time of day, the computer assumes you mean the day’s beginning (which is 12:00:00 AM).
If you leave out the date, the computer assumes you mean the beginning of modern times (which according to Microsoft is 12/30/1899).
To avoid pissing off people who don’t like those assumptions, the Print command avoids printing 12:00:00 AM and avoids printing 12/30/1899. For example, if you leave out the time of day and type this —
Dim x As Date
x = #12/31/2005#
Print x
x will be #12/31/2005 12:00:00 AM# but the Print command will print just:
12/31/2005
If you say —
x = Now
the computer will make x be the current date-with-time. For example, if the computer encounters that line while running the program on December 31, 2005 (at 30.16 seconds after 11:59 PM), x will become #12/31/2005 11:59:30 PM#. Instead of saying x = Now, you can say other things:
What you say What x will become
x = Now the date with time: #12/31/2005 11:59:30 PM#
x = Date just the date: #12/31/2005#
x = Time just the time: #11:59:30 PM#
x = Date$ the date, written with hyphens, as a string: “12-31-2005”
x = Time$ the time, written in 24-hour style, as a string: “23:59:30”
x = Timer the number of seconds since midnight: 86370.16
Object An Object is Form1 or Command1 or any other VB object.
For example, suppose you created a button called Command1. If you put this line in Form1’s subroutine, Command1’s caption will become “Click here for a joke”:
Command1.Caption = "Click here for a joke"
These lines do the same thing:
Dim x As Object
Set x = Command1
x.Caption = "Click here for a joke"
Notice that to make x equal an Object, you must say Set.
String A String is a collection of characters, such as “joy” or “I love you” or “aieee luf ya” or “76 trombones” or “GO AWAY!!!” or “xypw exr///746”. Here’s an example:
Dim x As String
x = "joy"
Print x
The computer will print:
joy
Since the string “joy” contains 3 characters, x consumes 3 bytes of RAM — plus 10 bytes to remember how long the string is. So altogether, x consumes 13 bytes of RAM.
Instead of saying “Dim x As String”, you can be more helpful by saying:
Dim x As String * 3
That says x will always be a string of 3 characters, so the computer doesn’t need to wonder how many characters x will have and doesn’t need to devote 10 bytes to that question. The x will consume 3 bytes of RAM, not 13.
If you say “Dim x As String * 3” and then try to say x = “father”, the computer will shorten “father” to 3 characters, so x will be “fat”. If you say “Dim x As String * 3” and then try to say x = “he”, the computer will lengthen “he” to 3 characters, so x will be h then e then a blank space.
If you say “Dim x As String * 3”, x will be a string of 3 characters and consume 3 bytes of RAM. If you say “Dim x As String * 4”,x will be a string of 4 characters and consume 4 bytes of RAM. The biggest string length you can specify is “Dim x As String 65526”.
If you say just “Dim x As String”, without putting a number after “String”, the computer will keep track of how long x is and consume as many bytes as needed for x — plus 10 extra bytes for remembering x’s length. For example, if x is “joy”, x will consume 3 bytes, plus 10 bytes for remembering x’s length, so x will consume 13 bytes of RAM altogether. If you say just “Dim x As String”, without putting a number after “String”, x can be a string up to 2 billion characters long.
If you say “Dim x As String” and try to say “x = 9 + 3.5”, the computer will try to make x be 12.5 but must turn x into a string, so x will become the string “12.5” (without any blank spaces).
Variant If you say —
Dim x As Variant
you’re being purposely vague: you’re saying that x could be anything (a Byte or Integer or Long or Currency or Single or Double or Boolean or Date or Object or String). For example, if you say “Dim x As Variant”, you can say x = 5000 and later change x by saying x = “joy”.
Saying “Dim x As Variant” is the same as saying just “Dim x” or saying nothing at all about x! That forces the computer to figure out, by itself, without human help, what kind of data x is. Such thinking will consume RAM:
While x is a number, the computer will consume a total of 16 bytes. (Some of those bytes are to remember the number’s digits, and some of those bytes are to remember what type of data the number is.)
While x is a string, the computer will consume 1 byte per character, plus 22 bytes (to remember the string’s length and type).
Multiple variables
If you want x to be a Byte, y to be a String, and price to be a Currency, say this —
Dim x As Byte
Dim y As String
Dim price As Currency
or say this:
Dim x As Byte, y As String, price As Currency
If you want x and y to both be Integers, say:
Dim x As Integer
Dim y As Integer
or say this:
Dim x As Integer, y As Integer
Do not say just “Dim x, y As Integer”, which means “Dim x As Variant, y As Integer”.
Suffix
The normal way to make x be a String is to say:
Dim x As String
An alternative way to make x be a String is to put a dollar sign after the x, so that you always write x$ instead of x. The dollar sign is called a suffix (or type-declaration character).
Here are the suffixes you can use:
Suffix Meaning
$ String
% Integer
& Long
! Single
# Double
@ Currency
Constants
Your subroutine can mention variables (such as x and y), commands (such as Print and If), operators (such as + and -), and constants (such as 3.7 and “I love you”).
You’ve learned that a variable (such as x) can have 11 types: Byte, Integer, Long, Currency, Single, Double, Boolean, Date, Object, String, or Variant. Each constant can have a type also. Here’s how the computer tells a constant’s type:
If the constant is enclosed in quotation marks (such as “I love you”), it’s a String.
If the constant is the word True or the word False, it’s a Boolean.
If the constant begins and ends with the symbol #, it’s a Date.
If the constant is the word Form1 or the name of another object you created, it’s an Object.
If the constant is a number, here’s what happens.…
If the number has no decimal point and no E and is between -32768 and 32767, it’s an Integer. If the number has no decimal point and no E and is between -2147483648 and 2147483647 but is not an Integer, it’s a Long. Any other number is a Double.
To force a number to be a Currency instead, put @ after the number, like this: 4.95@
To force a number to be a Single instead, put ! after the number, like this: 4.95!
To force a number to be a Byte instead, put the number in Cbyte(), like this: CByte(52)
To force a number to be a Double, even though it’s simple enough to be an Integer or Long, put .0 (or #) after the number, like this: 52.0 (or 52#). If you put .0 after the number, the computer will automatically change the .0 to #. To force a number to be a Long, even though it’s small enough to be an Integer, put & after the number (like this: 52&).
A constant cannot be a Variant, since is constant has a specific value but a Variant is vague.
VarType
Each type of constant has a code number:
Type of constant Code number
Integer 2
Long 3
Single 4
Double 5
Currency 6
Date 7
String 8
Object 9
Boolean 11
Byte 17
If you say Print VarType, the computer will examine a constant and tell you its code number. For example, if you say —
Print VarType(4.95@)
the computer will examine 4.95@, realize it’s a Currency, and print Currency’s code number, which is:
6
Here are more examples:
If you say Print VarType (“I love you”), the computer will examine “I love you”,
realize it’s a String, and print String’s code number, which is 4.
If you say Print VarType(30000), the computer will examine 30000,
realize it’s an Integer, and print Integer’s code number, which is 2.
If you say Print VarType(40000), the computer will examine 40000,
realize it’s a Long, and print Long’s code number, which is 3.
VarType of a variable If you say Print VarType(x), the computer will notice what type of variable x is and print its code number. For example, if you say —
Dim x As Currency
Print VarType(x)
the computer will print Currency’s code number, which is 6.
There is no code number for Variant. If x is a Variant, the computer will try to print the code number of x’s value. For example, if x is a Variant and you say —
x = 4.95@
Print VarType(x)
the computer will print Currency’s code number, which is 6.
If x is a Variant but doesn’t have a value yet, Print VarType(x) will print 0.
TypeName
If you say TypeName instead of VarType, the computer will say the type’s name instead of its code number.
For example, if you say —
Print TypeName(4.95@)
the computer will say:
Currency
Instead of saying “Object”, the computer will try to be more specific. For example, if you created a command button called Command1 and say —
Print TypeName(Command1)
the computer will say:
CommandButton
If x is a Variant but doesn’t have a value yet, Print TypeName(x) will print:
Empty
Operations
When you do math operations (add, subtract, multiply, divide, or exponents), here’s what kind of answer you get.
Exponents When you do exponents (using the symbol “^”), the answer is a Double.
Division When you divide one number by another (using the symbol “/”), here’s what happens:
If both numbers are short (Byte, Integer, or Single), the answer is a Single; otherwise, the answer is a Double.
Add, subtract multiply When you add, subtract, or multiply numbers (using the symbol + or - or *), here’s what happens:
If both numbers are the same type, the computer tries to make the answer be that same type.
If the numbers have different types from each other, the computer notices which type is more precise and tries to make the answer be that type. (For multiplication, here are the types from least precise to most precise: Byte, Integer, Long, Single, Currency, Double. For addition and subtraction: here are the types from least precise to most precise: Byte, Integer, Long, Single, Double, Currency.)
But if such an answer would produce an Overflow error (because the answer is too high a number to fit in that type), the computer switches the answer to a higher type: it switches Byte to Integer, switches Integer to Long, and switches Long (or Single) to Double. Another exception: if one number is a Single and the other number is a Long, the answer is a Double.
Adding strings You can add two Strings together: “hot” + “dog” is “hotdog”. That can be called “shoving the strings together”, but programmers call it “concatenating the strings”.
To avoid confusion and also make your program run faster, Microsoft recommends concatenating by using the symbol & instead of +, so you write:
"hot" & "dog"
For example, you can say —
Print "hot" & "dog"
or say:
x = "hot"
y = "dog"
Print x & y
Date arithmetic You can start with a Date and then add or subtract a number of days. For example, adding 1 means “the next day”, so that #12/29/2005# + 1 is #12/30/2005#.
Adding .25 means “a quarter of a day” (which is 6 hours), so that #12/29/2005 3PM# + .25 is #12/29/2005 9PM#. Another way to add 6 hours is to add #6:00#. Similarly, you can add 10 minutes by adding #0:10#.
(When you’ve typed such stuff and press the ENTER key afterwards, the computer will annoy you by changing #6:00# to #6:00:00 AM# and changing #0:10# to #12:10:00 AM#, but don’t worry: the computer will still print correct answers.)
General declarations
Normally, each subroutine has its own variables. For example, if Form1’s subroutine uses a variable called x, and Command1’s subroutine uses a variable that’s also called x, Form1’s x has nothing to do with Command1’s x. Form1’s x is stored in a different part of RAM from Command1’s x. If Form1 says x = 5, Command1’s x remains unaffected by that statement.
To prove that, try this experiment:
Make Form1’s subroutine says x = 5.
Create a Command1 button and make its subroutine say Print x.
When you run the program and click the Command1 button, the computer will not print 5. Instead it will print just a blank, because Command1’s x is unrelated to Form1’s x.
If you want Form1’s x to be the same as Command1’s x and use the same RAM, say “Dim x” in your program’s general declarations. Here’s how.…
Get Form1’s subroutine onto the screen. Above that subroutine, you see a box saying “Form”. Click that box’s down-arrow, then click “(General)”. Then type “Dim x” (or something more specific, such as “Dim x As Integer”).
By saying “Dim x” in your program’s general declarations (instead of in a subroutine), you’re saying that x has general scope (the x applies to all subroutines instead of just a single subroutine).
Def If you want all variables to be Integer, say —
DefInt A-Z
Put that line into your program’s general declarations. Here’s how.…
Get Form1’s subroutine onto the screen. Above that subroutine, you see a box saying “Form”. Click that box’s down-arrow, then click “(General)”, then type:
DefInt A-Z
Here are similar statements you can give:
Statement Meaning
DefInt A-Z all variables are Integer
DefLng A-Z all variables are Long
DefCur A-Z all variables are Currency
DefSng A-Z all variables are Single
DefDbl A-Z all variables are Double
DefObj A-Z all variables are Object
DefStr A-Z all variables are String
DefVar A-Z all variables are Variant
DefByte A-Z all variables are Byte
DefBool A-Z all variables are Boolean
DefDate A-Z all variables are Date
If you want most variables to be Integer but want price to be a Currency, say “DefInt A-Z” in your program’s general declarations but say “Dim price As Currency” underneath (in the general declarations or in whichever subroutine uses price).
Conversion functions
In the middle of a calculation, you can convert to a different type of data by using these conversion functions:
Function Meaning
CInt convert to Integer
CLng convert to Long
CCur convert to Currency
CSng convert to Single
CDbl convert to Double
CStr convert to String
CVar convert to Variant
CByte convert to Byte
CBool convert to Boolean
CDate convert to Date
For example, CInt(3.9) is “3.9 converted to the nearest Integer”, which is 4. If you say —
Print CInt(3.9)
the computer will print:
4
If you say —
Print CInt(3.9) + 2
the computer will print:
6
Arrays
To make x be a list of 3 items, say:
Dim x(3)
That says x is a list of 3 items. The 3 items are called x(1), x(2), and x(3).
For example, try making Form1’s subroutine say this:
Dim x(3)
x(1) = 7.9
x(2) = "I love you"
x(3) = x(1) - 5.9
Print x(2); x(3)
The top line says x is a list of 3 items. The lines below say x’s first item is the number 7.9, x’s second item is the string “I love you”, and x’s third item is the first item(7.9) minus 5.9, so it’s 2. The Print line line makes the computer print x’s second item (which is “I love you”) then x’s third item (which is 2), so the computer will print:
I love you 2
Instead of saying x(1) = 7.9, math books say:
x1 = 7.9
The lowered 1 is called a subscript.
In that example, the x is called an array. Definition: an array is a variable that has subscripts.
To make x be a list of 10 items, say:
Dim x(10)
To make x be a list of 1000 items, say:
Dim x(1000)
To make x be a list of a million items, say:
Dim x(1000000)
To make x to be a list of 10 items and make each item be a String, say:
Dim x(10) As String
To make x be a list of a million Integers, say:
Dim x(1000000) As Integer
Since each Integer consumes 2 bytes, that list of a million Integers consumes 2 million bytes, which is 2 megabytes. That’s much less RAM than saying just Dim x(1000000), which would create a list of a million Variants, at 16 bytes per Variant, 16 megabytes total.
Love and hate Let’s make x be this list of 7 strings: “love”, “hate”, “kiss”, “kill”, “peace”, “war”, “why”.
To do that, begin Form1’s subroutine by saying:
Dim x(7) As String
x(1) = "love"
x(2) = "hate"
x(3) = "kiss"
x(4) = "kill"
x(5) = "peace"
x(6) = "war"
x(7) = "why"
That says x’s first item is “love”, x’s second item is “hate”, etc.
To make the computer to print all those items, say:
For i = 1 To 7
Print x(i)
Next
That means: print all the items in x. The computer will print:
love
hate
kiss
kill
peace
war
why
Let’s lengthen the subroutine, so the computer prints all this:
love
hate
kiss
kill
peace
war
why
why love
why hate
why kiss
why kill
why peace
why war
why why
That consists of two verses. The second verse resembles the first verse, except that each line of the second verse begins with “why”.
To make the computer print all that, just add the shaded lines to the subroutine:
Dim x(7) As String
x(1) = "love"
x(2) = "hate"
x(3) = "kiss"
x(4) = "kill"
x(5) = "peace"
x(6) = "war"
x(7) = "why"
For i = 1 To 7
Print x(i)
Next
Print x
For i = 1 To 7 x
Print "why"; x(i)
Next x
The shaded Print line leaves a blank line between the first verse and the second verse. The shaded For…Next loop, which prints the second verse, resembles the For…Next loop that printed the first verse but prints “why” before each x(i).
Let’s add a third verse, which prints the words in reverse order:
why
war
peace
kill
kiss
hate
love
Before printing that third verse, print a blank line:
Then print the verse itself. To print the verse, you must print x(7), then print x(6), then print x(5), etc. To do that you could say:
Print x(7)
Print x(6)
Print x(5)
etc.
But this way is shorter:
For i = 7 To 1 Step -1
Print x(i)
Next
Tables Let’s make x be this table of Strings:
“dog” “cat” “mouse”
“hotdog” “catsup” “mousetard”
To do that, begin by saying:
Dim x(2, 3) As String
That says x will be a table having 2 rows and 3 columns of Strings.
Then tell the computer what Strings are in x. Type these lines:
x(1, 1) = "dog"
x(1, 2) = "cat"
x(1, 3) = "mouse"
x(2, 1) = "hotdog"
x(2, 2) = "catsup"
x(2, 3) = "mousetard"
That says the String in x’s first row and first column is “dog”, the String in x’s first row and second column is “cat”, etc.
If you’d like the computer to print all those Strings, type this:
For i = 1 To 2
For j = 1 To 3
Print x(i, j),
Next
Next
That means: print all the items in x. The computer will print:
dog cat mouse
hotdog catsup mousetard
Most programmers follow this tradition: the row’s number is called i, and the column’s number is called j. That example obeys that tradition. The “For i = 1 To 2” means “for both rows”; the “For j = 1 To 3” means “for all 3 columns”.
Notice i comes before j in the alphabet; i comes before j in x(i, j); and “For i” comes before “For j”. If you follow the i-before-j tradition, you’ll make fewer errors.
At the end of the first Print line, the comma makes the computer print each column at its own tab stop. The other Print line makes the computer press the ENTER key at the end of each row. The x is called a table or 2-dimensional array or doubly subscripted array.
Random numbers
Usually, the computer is predictable: it does exactly what you say. But sometimes, you want the computer to be unpredictable.
For example, if you’re going to play a game of cards with the computer and tell the computer to deal, you want the cards dealt to be unpredictable. If the cards were predictable — if you could figure out exactly which cards you and the computer would be dealt — the game would be boring.
In many other games too, you want the computer to be unpredictable, to “surprise” you. Without an element of surprise, the game would be boring.
Being unpredictable increases the pleasure you derive from games — and from art. To make the computer act artistic, and create a new original masterpiece that’s a “work of art”, you need a way to make the computer get a “flash of inspiration”. Flashes of inspiration aren’t predictable: they’re surprises.
Here’s how to make the computer act unpredictably.…
Rnd is a RaNDom decimal (bigger than 0 and less than 1) whose data type is Single. For example, it might be .6273649 or .9241587 or .2632801. Every time your program mentions Rnd, the computer concocts another decimal:
Print Rnd
Print Rnd
Print Rnd
The computer prints:
.7055475
.533424
.5795186
The first time your program mentions Rnd, the computer chooses its favorite decimal, which is .7055475. Each succeeding time your program mentions Rnd, the computer uses the previous decimal to concoct a new one. It uses .7055475 to concoct .533424, which it uses to concoct .5795186. The process by which the computer concocts each new decimal from the previous one is weird enough so we humans cannot detect any pattern.
How to print many decimals
These lines print 16 decimals:
For i = 1 To 16
Print Rnd
Next
Some of those decimals are numbers that end in “E-02”, which means “move the decimal point to the left, 2 places”.
These lines print 50 decimals:
WindowState = vbMaximized
For i = 1 To 50
Print Rnd
Next
The top line maximizes the window. To see all 50 decimals, your screen’s resolution must be at least 1024-by-768.
Here’s how to print 50 rows of decimals, 2 decimals per row, 100 decimals total:
WindowState = vbMaximized
For i = 1 To 50
Print Rnd; Tab(20); Rnd
Next
Here’s how to print 50 rows of decimals, 10 decimals per row, 500 decimals total:
WindowState = vbMaximized
For i = 1 To 50
For j = 1 To 181 Step 20
Print Tab(j); Rnd; x
Next x
Print x
Next
Percentages
When you print a list of decimals, about half the decimals will be less than .5, and about half will be more than .5.
Most of the decimals will be less than .9. In fact, about 90% will be.
About 36% of the decimals will be less than .36; 59% will be less than .59; 99% will be less than .99; 2% will be less than .02; a quarter of them will be less than .25; etc.
You might see some decimal twice, though most of the decimals will be different from each other.
Randomize
If you run one of those programs again, you’ll get exactly the same list of decimals again, in the same order.
If you’d rather see a different list of decimals, say Randomize at the subroutine’s top:
Randomize
WindowState = vbMaximized
For i = 1 To 50
For j = 1 To 181 Step 20
Print Tab(j); Rnd;
Next
Next
When the computer sees Randomize, the computer looks at the clock and manipulates the time’s digits to produce the first value of Rnd.
So the first value of Rnd will be a number that depends on the time of day, instead of the usual .7055475. Since the first value of Rnd will be different than usual, so will the second, and so will the rest of the list.
Every time you run the program, the clock will be different, so the first value of Rnd will be different, so the whole list will be different — unless you run the program at exactly the same time the next day, when the clock is the same. But since the clock is accurate to a tiny fraction of a second, the chance of hitting the same time is extremely unlikely.
Coin flipping
Here’s how to make the computer flip a coin:
Randomize
If Rnd < 0.5 Then Print "heads" Else Print "tails"
The Randomize line makes the value of Rnd depend on the click. The If line says there’s a 50% chance that the computer will print “heads”; if the computer does not print “heads”, it will print “tails”.
Until you run the program, you won’t know which way the coin will flip; the choice is random. Each time you run the program, the computer will flip the coin again; each time, the outcome is unpredictable. Try running it several times!
Love or hate?
Who loves ya, baby? These lines try to answer that question:
Randomize
x = InputBox("Type the name of someone you love")
If Rnd < 0.67 Then
Print x; " loves you, too"
Else
Print x; " hates your guts"
End If
The Randomize line makes the value of Rnd depend on the clock. The InputBox line makes the computer wait for the human to type a name. Suppose he types Suzy. Then x is “Suzy”. The If line says there’s a 67% chance that the computer will print “Suzy loves you, too”, but there’s a 33% chance the computer will instead print “Suzy hates your guts”.
Try running the program several times. Each time, input a different person’s name. Find out which people love you and which people hate your guts — according to the computer!
Random integers
If you want a random integer from 1 to 100, ask for 1 + Int(Rnd * 100). Here’s why:
Rnd is a decimal, bigger than 0 and less than 1.
So Rnd * 10 is a decimal, bigger than 0 and less than 10.
So Int(Rnd * 10) is an integer, at least 0 and no more than 9.
So 1 + Int(Rnd * 10) is an integer, at least 1 and no more than 10.
Guessing game These lines play a guessing game:
Randomize
MsgBox "I'm thinking of a number from 1 to 10."
ComputerNumber = 1 + Int(Rnd * 10)
AskHuman: guess = Val(InputBox("What do you think my number is?"))
If guess < ComputerNumber Then MsgBox "Your guess is too low.": GoTo AskHuman
If guess > ComputerNumber Then MsgBox "Your guess is too high.": GoTo AskHuman
Print "Congratulations! You found my number!"
The second line makes the computer say “I’m thinking of a number from 1 to 10.” The next line makes the computer think of a random number from 1 to 10. The InputBox line asks the human to guess the number.
If the guess is less than the computer’s number, the first If line makes the computer say “Your guess is too low” and then GoTo AskHuman, which lets the human guess again. If the guess is greater than the computer’s number, the second If line makes the computer say “Your guess is too high” and then GoTo AskHuman.
When the human guesses correctly, the computer arrives at the bottom line, which prints:
Congratulations! You found my number!
Dice These lines make the computer roll a pair of dice:
Randomize
Print "I'm rolling a pair of dice"
a = 1 + Int(Rnd * 6)
Print "One of the dice says"; a
b = 1 + Int(Rnd * 6)
Print "The other says"; b
Print "The total is"; a + b
The second line makes the computer say:
I'm rolling a pair of dice
Each of the dice has 6 sides. The next line, a = 1 + Int(Rnd * 6), rolls one of the dice, by picking a number from 1 to 6. The line saying “b = 1 + Int(Rnd * 6)” rolls the other. The bottom line prints the total.
Here’s a sample run:
I'm rolling a pair of dice
One of the dice says 3
The other says 5
The total is 8
Here’s another run:
I'm rolling a pair of dice
One of the dice says 6
The other says 4
The total is 10
Daily horoscope These lines predict what will happen to you today:
Randomize
Dim x(5)
x(1) = "wonderful"
x(2) = "fairly good"
x(3) = "so-so"
x(4) = "fairly bad"
x(5) = "terrible"
Print "You will have a "; x(1 + Int(Rnd * 5)); " day today!"
Those lines make x be a list of 5 fortunes. Since 1 + Int(Rnd * 5) is a random integer from 1 to 5, the x(1 + Int(Rnd * 5)) is a randomly chosen fortune. The computer will print —
You will have a wonderful day today!
or —
You will have a terrible day today!
or some in-between comment.
For inspiration, run that program when you get up in the morning. Then notice whether your day turns out the way the computer predicts!
Data files
Here’s a simple Form1 subroutine:
Print "eat"
Print 2 + 2
Print "eggs"
It makes the computer print this message onto your screen:
eat
4
eggs
Instead of printing that message onto your screen, let’s make the computer print the message onto your disk. Here’s how.…
Open For Output
This Form1 subroutine prints the message onto your hard disk, instead of onto your screen:
Open "joan.txt" For Output As 1
Print #1, "eat"
Print #1, 2 + 2
Print #1, "eggs"
Close
Those Print lines make the computer print the message onto your hard disk instead of onto your screen. Each line says Print #1, which means: print onto the hard disk.
The Open line is an introductory line that tells the computer where on the hard disk to print the message. The Open line says: find a blank place on the hard disk, call it joan.txt, and make joan.txt be file #1. So Print #1 will mean: print onto file #1, which is joan.txt.
(Instead of joan.txt, you can invent any other filename that ends in .txt.)
Any program that says Open should also say Close, so the bottom line says Close. The Close line makes the computer put some “finishing touches” on joan.txt, so that joan.txt becomes a perfect, finished file.
When you run that program, the computer will automatically put onto the hard disk a file called joan.txt that contains this message:
eat
4
eggs
After running that program, try this experiment:
Click “Start” (at the screen’s bottom left corner).
If you’re using Windows 95 or 98 or 98SE, click “Find” then “Files or Folders”. If you’re using Windows Me, click “Search” then “For Files or Folders”.
Type “joan.txt” (then press ENTER).
The computer will search drive C for joan.txt. It will probably find joan.txt is in C:\Program Files\MicrosoftVisual Studio\VB98. It will show an icon for joan. Double-click that icon.
The computer will show you what’s in joan.txt (by automatically running NotePad, which resembles WordPad). The computer will say:
eat
4
eggs
When you finish admiring that, close the joan-NotePad window (by clicking its X button). Then close the Find window (or Search Results window).
Open For Input
To see the message that’s in joan.txt, run this subroutine, which inputs from joan.txt and prints onto your screen:
Open "joan.txt" For Input As 1
Input #1, x
Print x
Input #1, y
Print y
Input #1, z
Print z
Close
The Open line prepares the computer to input from joan.txt.
The next line inputs x from joan.txt, so x is “eat”. The next line prints “eat” onto your screen’s Form1.
The next pair of lines input y from joan.txt (so y is 4) and print 4 onto Form1. The next pair of lines input z from joan.txt (so z is “eggs”) and print “eggs” onto Form1. So altogether, on your screen’s Form1 you’ll see:
eat
4
eggs
The Close line tells the computer that you’re done using joan.txt for a while (until you say Open again).
Open For Append
After you’ve put joan.txt onto the disk (so that joan.txt consists of “eat” and 4 and “eggs”), try running this subroutine:
Open "joan.txt" For Append As 1
Print #1, "good morning!"
Close
In the Open line, the word Append tells the computer to keep adding onto joan.txt. So when the computer comes to the Print line, it adds “good morning!” onto joan.txt, and joan.txt becomes this:
eat
4
eggs
good morning!
Erasing
For your next experiment, try running this program:
Open "joan.txt" For Output As 1
Print #1, "pickles are pleasant"
Close
Since the Open line does not say Append, the computer will not keep adding onto joan.txt. Instead, the computer erases everything that’s been in joan.txt. So when the computer finishes processing the Open line, joan.txt has become blank.
The Print line puts “pickles are pleasant” into joan.txt. So at the end of the program, joan.txt includes “pickles are pleasant” (but not “eat”, 4, “eggs”, and “good morning!”, which have all been erased).
Output, Input, Append
In the Open line, you can say Output or Input or Append. Here’s how they differ:
If the Open line says For Input, the program can say Input #1 but cannot say Print #1.
If the Open line says For Output, the program can say Print #1 but cannot say Input #1.
If the Open line says For Append, the program can say Print #1 but usually cannot say Input #1.
Here’s what happens if you say Open “joan.txt” and the file joan.txt exists already:
For Input makes the computer use joan.txt without changing joan.txt.
For Append makes the computer use joan.txt and lengthen it (by appending extra lines to its end).
For Output makes the computer erase joan.txt and then create a totally new joan.txt.
Here’s what happens if you say Open “joan.txt” when joan.txt doesn’t exist yet:
For Output or For Append makes the computer create joan.txt.
For Input makes the computer gripe and say “File not found”.
The following subroutine plays a trick: if joan.txt doesn’t exist yet, the subroutine creates joan.txt; if joan.txt exists already, the subroutine leaves joan.txt alone.
Open "joan.txt" For Append As 1
Close
Loops
This subroutine lets you put the names of all your friends onto the hard disk:
Open "friends.txt" For Output As 1
Do
FriendName = InputBox("Type a friend's name or the word 'end'")
If FriendName = "end" or FriendName = "" Then Exit Do
Print #1, FriendName
Loop
Close
End
Here’s how it works:
The Open line makes the computer create a friends.txt file on your hard disk.
The InputBox line makes the computer show an input box. The input box says “Type a friend’s name or the word ‘end’”. The input box also has a blank space (for you to type in) and buttons (marked “OK” and “Cancel”). Whatever you type in the blank space will be called FriendName (if you click “OK” afterwards). If you click “Cancel” instead, friend will be an empty string, “”.
The next line says: if FriendName is “end” or “”, exit from the Do loop.
The Print line makes the computer print the friend’s name into the friends.txt file. For example, if FriendName is Mary Williams (because you typed Mary Williams in the input box’s blank space then clicked “OK”), the computer will print the name Mary Williams into the friends.txt file.
The lines are in a Do loop, so that you can type as many names as you wish. (Remember to click “OK” after each name.)
When you’ve finished typing the names of all your friends (and clicked “OK” after each one), type the word “end” and click “OK” (or click “Cancel”). Then the If line will make the computer Exit from the Do loop, Close the file, and End the program.
This subroutine makes the computer look at the friends.txt file and copy all its names to your screen:
Open "friends.txt" For Input As 1
Do Until EOF(1)
Input #1, FriendName
Print FriendName
Loop
Close
Print "Those are all the friends."
Here’s how it works:
The Open line prepares the computer to input from the friends.txt file. The lines Do and Loop make the computer do the indented lines repeatedly. The first indented line makes the computer input a string from the file and call the string FriendName; so FriendName becomes the name of one of your friends. The next indented line prints that friend’s name onto your screen. Since those indented lines are in a loop, the names of all your friends are printed on the screen.
Eventually, the computer will reach the end of the file, and there won’t be any more names to input from the file. In the Do line, the “Until EOF(1)” means: if the computer reaches the End Of the File and can’t input any more names from it, the computer should stop looping and proceed to the line underneath Loop. That line makes the computer Close the file. Then the computer will print on your screen, “Those are all the friends.”
As that subroutine illustrates, to read from a file you create a Do loop. Above the loop, say Open for Input; below the loop, say Close; in the loop, say Input #1; next to the Do, say Until EOF(1).
LOF
In the middle of your subroutine, if you say Print LOF(1), the computer will tell you the Length Of the File: it will tell you how many bytes are in the file.
Multiple files
If you want the computer to handle two files simultaneously, use two Open statements.
At the end of the first Open statement, say “As 1”; at the end of the second Open statement, say “As 2”. For the second file, say Print #2 instead of Print #1, say Input #2 instead of Input #1, say EOF(2) instead of EOF(1), and say LOF(2) instead of LOF(1).
How to Close
The Close statement closes all files. To be more specific, you can say Close 1 (which closes just the first file) or Close 2 (which closes just the second).
Whenever you’re done using a file, Close it immediately. When you say Close, the computer puts finishing touches on the file that protect the file against damage.
Suppose that halfway through your program, you finish using file 2 but want to continue using file 1. Say Close 2 there, and delay saying Close 1 until later.
Long text
Let’s program the computer to give the human a big white box, let the human type an essay into the box, and then copy the essay to the hard disk.
Create a text box (by double-clicking the Text Box tool). Enlarge it (by dragging its handles), until it’s nearly as large as Form1 (but leave a blank inch to the right of it, for an OK button). Make it be blank (by pressing the SPACE bar then the BACKSPACE key). Make it be MultiLine (by clicking MultLine then pressing T). Give it scroll bars (by clicking ScrollBars then the ScrollBars down-arrow then “2 - Vertical”).
Below the text box, put an OK button. Here’s how:
Double-click the Command Button tool. That creates a command button called Command1. Put that button below the text box (by dragging). Make the button’s caption be “OK” (by typing “OK”).
Make the OK button’s subroutine say this:
Open "essay.txt" For Output As 1
Print #1, Text1.Text
Close
End
Then run the program (by pressing F5). Click in the big white box. Type your essay there. (At the end of each paragraph, press ENTER twice.) When you’ve finished typing your essay, click the OK button. That makes the computer do the OK button’s subroutine (which copies your text to a file called “essay.txt” then ends the program).
To prove that the program worked, do this:
Click “Start” (at the screen’s bottom left corner).
If you’re using Windows 95 or 98 or 98SE, click “Find” then “Files or Folders”. If you’re using Windows Me, click “Search” then “For Files or Folders”.
Type “essay.txt” (then press ENTER).
The computer will search drive C for essay.txt. It will show an icon for essay. Double-click that icon.
The computer will show you what’s in essay.txt. It’s the essay you wrote!
If a paragraph is long, you might see just part of it on the screen. To see the rest of it, use the horizontal scroll bar (underneath the essay) or do this: click Edit then put a check mark in front of Word Wrap (by clicking Word Wrap).
When you finish admiring your essay, close the essay-NotePad window by clicking its X button. (If the computer asks “Do you want to save the changes?”, press ENTER.). Then close the Find window (or Search Results window).
In your VB program, the OK button copies from the text box to essay.txt. Let’s add a Retrieve button that copies in the opposite direction, from essay.txt to the text box. To do that, create another command button, put it to the right of the OK button, make its caption be Retrieve, and make its subroutine say this:
Open "essay.txt" For Input As 1
Do Until EOF(1)
Line Input #1, x
Text1.Text = Text1.Text & x & vbCrLf
Loop
Close
The Open line makes the computer find “essay.txt”. The Do Until EOF(1) line makes the computer repeat the loop until the computer reaches the end of the file essay.txt. The Line Input command makes the computer input a whole line from essay.txt (even if the line contains commas), and makes that line be called x. The next line makes the text box’s text become whatever was in the text box before, plus the line x, plus a carriage return and line feed (to mark the end of the line).