This chapter comes from the 33rd edition of the "Secret Guide to Computers & Tricky Living," copyright by Russ Walter. To read the rest of the book, look at www.SecretFun.com.

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:

VB 2, VB 3, VB 4, VB 5, VB 6

VB 7     (also called VB.Net)

VB 7.1  (also called VB.Net 2003)

VB 8     (also called VB 2005)

VB 9     (also called VB 2008)

VB 10   (also called VB 2010)

VB 11   (also called VB 2012)

VB 14   (also called VB 2015)

The most traumatic change was the switch from VB 6 to VB 7: programs written for VB 6 must be rewritten to work with VB 7.

This chapter explains the newest version: VB 2015.

Visual Basic is part of Visual Studio, which is Microsoft’s suite of programming languages. Visual Studio includes Visual Basic, Visual C++, Visual C#, and other programming tools.

Microsoft lets you get Visual Studio free! The main free version is called Visual Studio Community. You can copy it from Microsoft’s Website. It’s free just if you promise to use it either individually (not in a big company’s team) or non-commercially (just to study). Visual Studio Community improves on an older stripped-down version, called Visual Studio Express.

Before you read this chapter and study VB, prepare yourself! Do 2 prerequisite activities:

Learn QBasic or QB64, which are much easier than VB. I explained them on pages 507-561. 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 65-131, 137-158, and 231-249. Read and practice whichever of those Windows programs you have access to.


VB uses these commands (which resemble QBasic’s):

VB command                                       Page

Beep()                       566

Case "fine"                  573

ColorDialog1.ShowDialog()     584

Console.ReadKey()            586

Console.WriteLine(5 + 2)      586

Console.Write(5 + 2)         586

Debug.Print(5 + 2)           586

Dim x                        567

Dim x As Integer             595

Dim x As Integer = 7         599

Dim x = 7                    599

Dim x() = {81, 52, 207, 19}   600

Dim x(2) As Double           599

Do                       586, 590

document.Clear()             589

document.Copy()              590

document.Cut()               589

document.LoadFile…           588

document.Paste()             590

document.SaveFile…           588

Else                         571

ElseIf age < 100 Then        571

End                    568, 573

End Class                    563

End If                       571

End Module                   586

End Select                   573

End Sub                  563, 573

Exit Do                      591

Exit Sub                     573

For Each i In x              600

For x = 1 To 5               592

For x = 15 To 17 Step .1      593

GoTo joe                     590

If age < 18 Then         570, 571

Imports System.Math          599

Loop                     586, 590

Loop Until guess = "pink"     591

Module Module1               586

MsgBox("Hair looks messy")    568

My.Computer…WriteAllText…     587

Next                         592

OpenFileDialog1.ShowDialog()    588

Option Explicit Off          585

PrintForm1.Print()       563, 586

Private Sub Form1_Load…  563, 576

Public Class Form1           563

Randomize()                  601

RichTextBox1.SaveFile…       587

Select Case feeling          573

SaveFileDialog1.ShowDialog()    588

Sub Main()                   586

Text = 4 + 2                 563

x = 47                       567

? 5+2                        586

'Yeah, this is an example     585

VB uses these functions (which resemble QBasic’s):

VB function                       Value         Page

Chr(13)            Enter key        579

CInt(3.9)          4                     600

ColorDialog1.Color  varies              584

Fix(3.89)          3.0                 594

GetSelected(0)      varies              580

IIf(age < 18…       varies              572

InputBox("Name?")   varies              569

Int(3.89)          3.0                 594

Math.Abs(-3.89)     3.89                594

Math.Ceiling(3.89)  4.0                 594

Math.PI            about 3.14      594

Math.Round(3.89)    4.0                 594


Math.Sign(3.89)     1                     594

Math.Sqrt(9)       3.0                  594

My…LocalTime       varies              584

My…MyDocuments      Docu. folder    587

My…ReadAllText      varies              587

MsgBox("Love me?"…  varies              572

Now                varies              597

Rnd                varies              601

TypeName(4.95D)     "Decimal"        599

Val("7")           7                    569

VarType(4.95D)      14                  598

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

Button         576

CheckBox       577

ColorDialog    584

ComboBox       582

Form1          563

Form2          583

Label          579

ListBox        580

MenuStrip      588

NumericUpDown   581

OpenFileDialog  589

PictureBox     582

PrintForm      586

RadioButton    578

RichTextBox    581

SaveFileDialog  587

TextBox        581

Timer          583

ToolStrip      589

WebBrowser     583

Each object has properties, which you can manipulate:

VB property             Object                Page

BackColor      Form1     566, 574

Checked        CheckBox      577

DecimalPlaces   NumericUpDown 582

Dock           RichTextBox   581

DropDownStyle   ComboBox       582

EnableAutoDrag… RichTextBox   581

Enabled        Timer         583

FormBorderStyle Form1         575

Image          PictureBox    582

Interval       Timer         583

MaximizeBox    Form1         575

Maximum        NumericUpDown 582

Minimum        NumericUpDown 582

MultiLine      TextBox       581

(Name)         RichTextBox1  588

Opacity        Form1         575

PasswordChar   TextBox       581

ScrollBars     TextBox       581

SelectedIndex   ListBox       580

SelectedItem   ListBox       580

SelectionMode   ListBox       580

Size           Form1         575

SizeMode       PictureBox    582

StartPosition   Form1         575

Text           Form1     563, 574

Url            WebBrowser    583

Value          NumericUpDown 581

Visible        Form2         583

WindowState    Form1     566, 574

Fun

Let’s have fun programming!

Copy the Community

Here’s how to copy Visual Studio Community 2015 (including Visual Basic 2015) to your hard disk, using Windows 10. (Windows 7, 8, and 8.1 are also acceptable and act similarly.)

Using Microsoft Edge (or Internet Explorer), go to VisualStudio.com. Tap (or click) “Download Community 2015” then “No thanks” then “Save” then “Run”.

The computer will say “Initializing setup” then “Choose”. Tap the “Install” button then “Yes”.

The computer will say “Acquiring” and “Applying”. About 33 minutes later (depending on the speed of your computer and Internet connection), the computer will say “Setup Completed!”

Tap “Restart Now”. The computer will say “Restarting”. The screen will go black. Then computer will say “Please wait”. The computer will ask you to log in again (by typing your password).

If the computer asks “How do you want to open this?” tap “OK”.

The computer will say “Welcome to Visual Studio”.Close the Microsoft Edge (or Internet Explorer) window (by clicking the X at the screen’s top-right corner).

Start Visual Studio

To start using Visual Studio, type “vi” in the Windows 10 Search box (which is next to the Windows Start button) then click “Visual Studio 2015: Desktop app”.

If you haven’t used Visual Studio before, the computer says “Sign in”. To reply, do this:

Click the “Sign in” button. Type your email address and press Enter. Type your Microsoft account’s password and press Enter. The computer says “We’re preparing for first use”.

The computer says “Visual Studio.” After a delay, you see the “Start Page” window.

Create simple programs

Click “New Project” (which is near the screen’s left edge) then “Visual Basic then “Windows Forms Application”.

Double-click in the Name box (which is near the screen’s bottom). Type a name for your project (such as Funmaker). At the end of your typing, press the Enter key.

You see an object, called the Form1 window. Double-click in that window (below “Form1”). That tells the computer you want to write a program (subroutine) about that window.

The computer starts writing the subroutine for you. The computer writes:


Public Class Form1

    Private Sub Form1_Load…

 

    End Sub

End Class

The line saying “Private Sub Form1_Load” is the subroutine’s header. The line saying “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 —

        Text = 4 + 2

The computer automatically indents that line for you, so the subroutine becomes:

    Private Sub Form1_Load…

        Text = 4 + 2

    End Sub

To run your program, click “Start” (which is at the screen’s top center)
or press the F5 key. (If the “F5” is blue or tiny or on a new computer by Microsoft, HP, Lenovo, or Toshiba, that key works just while you hold down the Fn key, which is left of the Space bar.) Then you see the Form1 window again; but instead of saying “Form1”, it says the text’s 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 Form1_Load…

        Text = 4 + 2

    End Sub

Edited example Let’s edit that subroutine, so instead of saying the answer to 4 + 2, it will say 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 Form1_Load…

        Text = 79 + 2

    End Sub

Run that program by clicking “Start”. Then the Form1 window shows the new answer:

81

When you finish admiring that, click Form1’s X button.

To make the computer subtract 3 from 7, change the text line to this:

        Text = 7 - 3

When you run the program (by clicking “Start”), the Form1 window will show the answer:

4

To make the computer do -26.3+1, change the text line to this:

        Text = -26.3 + 1

The Form1 window will show the answer:

-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:

        Text = 2 * 6

The Form1 window will show:

12

Divide To divide, use a slash. So to divide 8 by 4, type this:

        Text = 8 / 4

The Form1 window will show:

2

To divide 2 by 3, type this:

        Text = 2 / 3

The Form1 window will show:

0.6666…

Maximize the Form1 window (by clicking its maximize button, which is next to its X). That makes the Form1 window consume the whole screen temporarily and show:

0.666666666666667

When you finish admiring that, return the Form1 window to its normal size (by clicking its Restore Down button, which is next to its X).

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 “Text”. The computer will capitalize them automatically, eventually. For example, if you type “text” instead of “Text”, the computer will change “text” to “Text” when you type the equal sign afterwards.

You don’t need to finish typing computer words such as “Text”. The computer will finish typing them for you, automatically, eventually, if the computer can deduce what you meant. For example, you can type “te” instead of “Text”; the computer will change “te” to “Text” when you type the equal sign afterwards.


Instead of typing computer words, you can choose them from lists. For example, instead of typing “Text”, you can do this:

Type the letter “t”. You’ll see a list of computer words that begin with “t”. (To see that whole list, click the list’s up-arrow & down-arrow or press the keyboard’s up-arrow & down-arrow keys.) If you type “te”, you’ll see a list of computer words that begin with “te”. In a list, when you see the word you want, either double-click the word or do this: highlight the word (by clicking it) then press the keyboard’s Tab key.

You don’t need to put spaces around symbols, such as “=” and “+”. The computer will insert those spaces automatically, when you end the line (by clicking “Start” or pressing the Enter key or down-arrow key or clicking a different line).

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.

Use decimals for big answers The computer sometimes has difficulty handling answers bigger than 2,000,000,000, which in modern English is called “2 billion.” To avoid difficulty, put a decimal point in any problem whose answer might be bigger than 2 billion.

For example, suppose you want the computer to multiply 3000 by 1000000. Since the answer to that problem is 3 billion, which is bigger than 2 billion, you should put a decimal point in that problem, like this:

        Text = 3000 * 1000000.0

After typing a decimal point, you must type a digit (such as 0).

Suppose you forget to insert a decimal point and say just this:

        Text = 3000 * 1000000

When you try to run the program (by clicking “Start”), the computer will complain in 3 ways:

It will put a squiggly red line under the “3000 * 1000000”.

The screen’s bottom will say “Constant expression not representable in type ‘Integer’.”

The screen’s middle will say, “There were build errors. Would you like to continue and run the last successful build?” To reply, click “No” then fix your error (by inserting .0) and click “Start” again.

E notation If the computer’s answer is huge (at least a quadrillion, which is 1000000000000000) or tiny (less than .0001), the computer will put 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 .0001). 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” or “” (which is the symbol for infinity) or “NaN” (which means “Not a Number”).

For example, if you say —

        Text = 1E309

the computer will put a squiggly red line under “1.0E+309”, screen’s bottom will say “Overflow”, and the screen’s middle will say “There were build errors” and wait for you to click “No”.

Dividing by 0 If you ask the computer to divide by 0, the computer will have difficulty.

For example, if you say —

        Text = 5 / 0

the computer will try to divide 5 by 0, give up (because you can’t divide by 0), and say the answer is “∞”.

If you say —

        Text = -5 / 0

the computer will try to divide -5 by 0, give up (because you can’t divide by 0), and say the answer is “-∞”.

If you say —

        Text = 0 / 0

the computer will try to divide 0 by 0, give up (because you can’t divide by 0), get confused, and say the answer is “NaN” (which means “Not a Number”).

The tiniest decimal The tiniest decimal the computer can handle accurately is 1E-308 (which is a decimal point followed by 308 digits, 307 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 whom 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 —

        Text = 2 + 3 * 4

the computer will think you mean “2 plus three fours”, so it will do 2 + 4 + 4 + 4 and display this answer:

14

The computer will not display 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 —

        Text = 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:

        Text = 2 + 3 * 4

 

                    12

So the problem becomes 2 + 12, which is 14, which the computer will display.

For another example, suppose you type:

        Text = 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:

        Text = 10 - 2 * 3 + 72 / 9 * 5

 

                      6         40

So the problem becomes 10 - 6 + 40, which is 44, which is the answer the computer will display.

Parentheses You can use parentheses the same way as in algebra. For example, if you type —

        Text = 5 - (1 + 1)

the computer will compute 5 - 2 and print:

3

You can put parentheses inside parentheses. If you type —

        Text = 10 - (5 - (1 + 1))

the computer will compute 10 - (5 - 2), which is 10 - 3, and will display:

7

Strings

Let’s make the computer fall in love. Let’s make it say, “I love you”. To do so, type this in your subroutine:

        Text = "I love you"

Type that carefully:

Type the word Text, then a blank space, then an equal sign, then another blank space. 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 clicking “Start”), it will make the text (at the top of Form1’s window) display:

I love you

You can change the computer’s personality. For example, if you edit the subroutine to make it become —

        Text = "I hate you"

the computer will reply:

I hate you

Notice that to make a subroutine 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 —

        Text = "aieee luf ya"

the computer will still copy the message (without worrying about what it means); the computer will make Form1 say:

aieee luf ya

Type faster Instead of typing —

        Text = "I love you"

you can type just this:

        text="I love you

The computer automatically capitalizes the first letter (T) and types the second quotation mark. Before the computer runs the program, the computer will also put spaces around the equal sign.


Red strings While you’re typing the subroutine,
the computer makes each string look red (and each computer word look blue).

Those colors appear just while you’re looking at the subroutine you’ve been typing. When you run the program, the program’s answers (and other results) appear black.

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 in your subroutine put the string in quotation marks.

Strings versus numbers The computer can handle two types of expressions: strings and numbers. In your subroutine, put strings (such as “joy” and “I love you”) in quotation marks. Numbers (such as 4 + 2) do not go in quotation marks.

Combine strings You can combine strings:

        Text = "fat" & "her"

The computer will combine “fat” with “her”, so the computer will display:

father

You can combine a string with a number:

        Text = "The lucky number is " & 4 + 2

The computer will display “The lucky number is ” then the answer to this math problem: 4 + 2. The computer will display:

The lucky number is 6

When combining a string with a number, make the computer leave a space between the string and the number, by putting a space before the last quotation mark.

Combining strings or numbers (by using the symbol “&”) is called concatenating.

When typing the symbol “&” to concatenate,
press the keyboard’s Space bar before and after the “&”. If you rely on the computer to put those spaces in automatically, you’ll be sorry, because the symbol “&” without spaces can have a different meaning, and the computer will occasionally guess wrong about which “&” you meant.

Accidents Suppose you accidentally put the number 2 + 2 in quotation marks, like this:

        Text = "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; Form1 will say:

2 + 2

It will not say 4.

Suppose you want the computer to show the word “love” but you accidentally forget to put the string “love” in quotation marks, and type this instead:

        Text = love

Since you forgot the quotation marks, the computer is confused. Whenever the computer is confused, it either gripes at you or says zero. In this particular example, here’s how the computer gripes at you: it puts a red squiggly line under “love,” and, when you run the program, it makes the screen’s middle say “There were build errors” and makes screen’s bottom say:

'love' is not declared.


 

Display a quotation mark The symbol for inches is ". Let’s make Form1 say:

The nail is 2" long.

This Text command does not work:

        Text = "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:

        Text = "The nail is 2"" long."

The symbol "" means: display a quotation mark. That Text line makes Form1 display:

The nail is 2" long.

Here’s the rule: to display a quotation mark ("), put the symbol "" in your Text statement.

Let’s make the computer display this sentence:

I saw "Hamlet" last night.

To display the quotation mark before “Hamlet”, you must type "". To display the quotation mark after “Hamlet”, you must type "". So type this:

        Text = “I saw ""Hamlet"" last night."

Color

Normally, the Form1 window’s middle is a big blank area that’s nearly white (very light gray). To make it red instead, put this line in your subroutine:

        BackColor = Color.Red

For example, to make the window’s title say “I love you” and make the window’s background color be red, put both of these lines in your subroutine —

        Text = "I love you"

        BackColor = Color.Red

so the whole subroutine looks like this:

Public Class Form1

    Private Sub Form1_Load…

        Text = "I love you"

        BackColor = Color.Red

    End Sub

End Class

The computer understands these color names:

Yellow, Gold, Goldenrod, LemonChiffon

Orange, Brown, Chocolate, Tan

Red, Pink, DeepPink, Crimson

Purple, Violet, Magenta, Orchid

Blue, Cyan, Navy, DeepSkyBlue

Green, Lime, Chartreuse, Khaki

White, Gray, Black, Silver

It understands many others, too: altogether, it knows the names of 147 colors. You’ll see the complete list when you’ve typed:

        BackColor = Color.

(Use the list’s up-arrow & down-arrow.)

Don’t put spaces in the middle of a color name: type “DeepSkyBlue”, not “Deep Sky Blue”.

Beep

To make the computer beep (play 3 musical notes through the computer’s speakers), put this line in your subroutine:

        Beep()


Multi-statement line

In your subroutine, a line can include many statements separated by colons, like this:

        Text = "I love you" : BackColor = Color.Red

That line means the same thing as:

        Text = "I love you"

        BackColor = Color.Red

Maximize

To maximize the Form1 window (so it consumes the whole screen), put this line in your subroutine:

        WindowState = 2

For example, let’s make the computer say “You turned me on, and I love you!” and maximize the Form1 window (so the human can see all that). Just put both of these lines in your subroutine:

        WindowState = 2

        Text = "You turned me on, and I love you!"

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 All button. (It looks like 2 floppy disks that are tiny. It’s near the screen’s top, below the “t” in “Project”.) That makes sure your program is saved. (It’s saved in its own folder, which is in the Projects folder, which is in the
Visual Studio 2015 folder, which is in the Documents folder, which is on drive C.)

Afterwards, if you make further changes to the program, click the Save All 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 the New Project button (which is near the screen’s top-left corner, below the word “View”, and shows a yellow sunburst before 2 sheets of paper). Then click “Windows Forms Application”, double-click in the Name box, type a name for the new program, and press the Enter key.

If the previous program wasn’t saved, the computer says “Save changes”. If you want to save the previous program, click “Yes”; otherwise, click “No”.)

Exit When you finish using Visual Studio, click the X button that’s in the screen’s top right corner.

Open When you start using Visual Studio, look at the the word “Recent” (near the screen’s left edge). Below “Recent”, you see a list of programs you used recently. If you want to use or edit one of those programs, click that program’s name. Either run the program again (by clicking “Start”) or edit the program’s commands.

Run the .exe file When the computer ran your program, it made an .exe file (called Funmaker.exe), which you can run again without going into Visual Studio. Here’s how:

Exit from Visual Studio. In the Windows 10 search box (which is next to the Windows Start button), type “Funmaker”. Tap “Funmaker: File Folder in Projects”. Double-click the “Funmaker” folder then “bin” then “Debug” then the first “Funmaker” (which says its type is “Application”).


Variables

A letter can stand for a number, a string, or other things.

For example, x can stand for the number 47, as in this subroutine:

        Dim x

        x = 47

        Text = x + 2

The top line (Dim x) warns the computer that x will stand for something. (The “Dim” comes from the word “Dimension”.)

The second line (x = 47) says x stands for the number 47. In other words, x is a name for the number 47. Warning: if you forgot to type the top line (Dim x), the computer refuses to let you type the second line (x = 47).

The bottom line (Text = x + 2) makes the computer display x + 2. Since x is 47, the x + 2 is 49; so the computer will display 49. That’s the only number the computer will display; it will not display 47.

Jargon

A letter standing for something is called a variable (or name or identifier). A letter standing 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              47

Then when the computer encounters the line “Text = x + 2”, the computer will display what’s in box x, plus 2; so the computer will display 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 automatically puts spaces around the equal sign.

More examples

Here’s another subroutine:

        Dim y

        y = 38

        Text = y - 2

The top line says y is a variable. The next line says y is 38. The bottom line says to display y - 2. Since y is 38, the
y - 2 is 36; so the computer will display 36.

Another example:

        Dim b

        b = 8

        Text = b * 3

The top line says b is a variable. The next line says b is 8. The bottom line says to display b * 3, which is 8 * 3, which is 24; so the computer will display 24.

One variable can define another:

        Dim n, d

        n = 6

        d = n + 1

        Text = n * d

The top line says n and d are variables. The next 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 display n * d, which is 6 * 7, which is 42; so the computer will display 42.

Changing a value

A value can change:

        Dim k

        k = 4

        k = 9

        Text = k * 2

The second line says k is 4, but the next line changes k’s value to 9, so the bottom line displays 18.

When you run that subroutine, here’s what happens inside the computer’s RAM. The second 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 (Text = k * 2) displays 18.

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:

        Dim x

        x = "I love you"

        Text = x

The top line warns the computer that x will stand for something. The next line says x stands for the string “I love you”. The bottom line makes the computer display:

I love you

In that subroutine, x is a variable. Since it stands for a string, it’s called a
string variable.

You can combine strings:

        Dim x

        x = "so"

        Text = x & "up"

(When typing that example, you must leave a space before the ampersand, to avoid confusion.) Since the second line says x is “so”, the bottom line will make Text be “so” & “up” and display this:

soup

If you insert a space by typing “ up” instead of “up”, like this —

        Dim x

        x = "so"

        Text = x & " up"

the computer will display:

so up

Long variable names

A variable’s name can be a letter (such as x) or a longer combination of characters, such as:

CityPopulationIn2001

For example, you can type:

        Dim CityPopulationIn2001

        CityPopulationIn2001 = 30716

        Text = CityPopulationIn2001 + 42

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.

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) but 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 appears in front of all other windows (so they’re covered up) 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.

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, which closes the form and ends the program.

End program automatically To please the human, make the computer click Form1’s X button and end the program, by putting this command under the MsgBox line —

        End

so your subroutine looks like this:

        MsgBox(“Warning: your hair looks messy today”)

        End

The top line makes the message box say “Warning: your hair looks messy today” then wait for the human to click OK. The bottom line ends the program (without requiring the human to click an X button).

Putting End under MsgBox makes the screen look like this:

Public Class Form1

    Private Sub Form1_Load…

        MsgBox(“Warning: your hair looks messy today”)

        End

    End Sub

End Class

Try it!

That End line is helpful. If you omit it and say just —

        MsgBox("Warning: your hair looks messy today")

here’s what happens when the 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 below the MsgBox line. The End line makes the computer stop running the program and automatically click the X button.

Faster typing If you type just —

        ms(

the computer will automatically change it to:

        MsgBox(

Add an icon To make the message box fancier, say vbExclamation, like this:

        MsgBox("Warning: your hair looks messy today", vbExclamation)

        End

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

(in a blue circle)    vbInformation

(in a blue circle)    vbQuestion

Math A message box can do math. For example, if you write a subroutine that says —

        MsgBox(4 + 2)

and then run the program (by clicking “Start”), the computer will create a message box that displays the answer, 6.


Input box

For a wild experience, type this subroutine:

Dim x

x = InputBox("What is your name?")

Text = "I love " & x

Run the program (by clicking “Start”). 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 appears in front of all other windows (so they’re covered up) and is centered on the screen. 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 —

Sue

x will be Joan. Then the Text line will make Form1 try to say:

I love Joan

To let the subroutine handle names that are long, maximize the Form1 window, by inserting this line —

WindowState = 2

so the subroutine becomes:

Dim x

x = InputBox("What is your name?")

WindowState = 2

Text = "I love " & x

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 says their sum:

Dim x, y

x = Val(InputBox("What is the first number?"))

y = Val(InputBox("What is the second number?"))

Text = x + y

When you run the program (by clicking “Start”), 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 says the sum of the numbers. For example, if the first number was 7 and the second number was 2, the computer will display 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 display this longer string:

72

Predict your future This subroutine makes the computer predict your future:

Dim y

y = Val(InputBox("In what year were you born?"))

WindowState = 2

Text = "In the year 2030, you'll turn " & 2030 – y & " years old."

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 2030, you'll turn 68 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:

Dim t

t = Val(InputBox("How many tickets?"))

WindowState = 2

Text = "The total price is $" & t * 2.79

Conversion These lines convert feet to inches:

Dim f

f = Val(InputBox("How many feet?"))

WindowState = 2

Text = f & " feet = " & f * 12 & " inches"

When you run the program, the computer asks “How many feet?” If you answer —

3

the computer will say:

3 feet = 36 inches

Trying to convert to the metric system? These lines convert inches to centimeters:

Dim i

i = Val(InputBox("How many inches?"))

WindowState = 2

Text = i & " inches = " & i * 2.54 & " centimeters"

Nice day today, isn’t it? These lines convert the temperature from Celsius to Fahrenheit:

Dim c

c = Val(InputBox("How many degrees Celsius?"))

WindowState = 2

Text = c & " degrees Celsius = " & 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 say:

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 commands

A subroutine is a list of commands you want the computer to obey. Here’s how to control which commands the computer obeys, and when, and in what order.

If

This subroutine makes the computer discuss the human’s age:

Dim age

age = Val(InputBox(“How old are you?”))

MsgBox("I hope you enjoy being " & age)

End

When that program is run (by clicking “Start”), 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 say:

I hope you enjoy being 15

After the human reads that message in the message box, the human should get out of the message box (by clicking the message box’s “OK” or pressing the Enter key). Then the computer will automatically close Form1.

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 MsgBox("You are still a minor")

so the subroutine looks like this:

Dim age

age = Val(InputBox(“How old are you?”))

MsgBox("I hope you enjoy being " & age)

If age < 18 Then MsgBox("You are still a minor")

End

For example, if the human runs the program and says —

15

the computer will say —

I hope you enjoy being 15

and then say:

You are still a minor

(At the end of each sentence, the computer waits for the human to click the message box’s OK.)

If instead the human says —

25

the computer will say just:

I hope you enjoy being 25

In that program, the most important line is:

If age < 18 Then MsgBox(“You are still a minor")

That line contains the words If and Then. Whenever you say “If”, you must also say “Then”. Don’t 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:

MsgBox("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:

Dim age

age = Val(InputBox(“How old are you?”))

MsgBox("I hope you enjoy being " & age)

If age < 18 Then MsgBox("You are still a minor") Else MsgBox("You are an adult")

End

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

and then (after you click “OK”):

You are an adult

Multi-line If If the age is less than 18, here’s how to make the computer say “You are still a minor” and also say “Ah, the joys of youth”:

If age < 18 Then MsgBox("You are still a minor") : MsgBox("Ah, the joys of youth")

Here’s a more sophisticated way to say the same thing:

If age < 18 Then

    MsgBox("You are still a minor")

    MsgBox("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 says If and Then (with nothing after Then). The computer will type the word “Then” for you, if you forget to type it yourself.

The computer indents the middle lines for you. They’re called the block and typically say MsgBox.

The bottom line says End If. The computer automatically types it for you.

In the middle of a multi-line If, you can say Else:

If age < 18 Then

    MsgBox("You are still a minor")

    MsgBox("Ah, the joys of youth")

Else                            

    MsgBox("You are an adult")     x

    MsgBox("We can have adult fun")

End If

That means: if the age is less than 18, then say “You are still a minor” and “Ah, the joys of youth”; otherwise (if age not under 18) say “You are an adult” and “We can have adult fun”. The computer automatically unindents the word “Else”.

ElseIf Let’s make the computer do this:

If age is under 18, say “You’re a minor”.

If age is not under   18 but is under 100, say “You’re a typical adult”.

If age is not under 100 but is under 125, say “You’re a centenarian”.

If age is not under 125, say “You’re a liar”.

Here’s how:

If age < 18 Then

    MsgBox("You're a minor")

ElseIf age < 100 Then

    MsgBox("You're a typical adult")

ElseIf age < 125 Then

    MsgBox("You're a centenarian")

Else

    MsgBox("You're a liar")

End If


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 type, “If age is either 7 or 8, say the word wonderful”:

If age = 7 Or age = 8 Then MsgBox("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 MsgBox("wonderful")

(because “age = 7” and “age = 8” are conditions)

Wrong: If age = 7 Or 8 Then MsgBox("wonderful")

(because “8” is not a condition)

And The computer understands the word And. Here’s how to type, “If age is more than 5 and less than 10, say you get hamburgers for lunch”:

If age > 5 And age < 10 Then MsgBox("you get hamburgers for lunch")

Here’s how to type, “If score is at least 60 and less than 65, say you almost failed”:

If score >= 60 And score < 65 Then MsgBox("you almost failed")

Here’s how to type, “If n is a number from 1 to 10, say that’s good”:

If n >= 1 And n <= 10 Then MsgBox("that's good")

Immediate If Here’s a shortcut. Instead of saying —

If age < 18 then Text = "Minor" else Text = "Adult"

you can say:

Text = IIf(age < 18, "Minor", "Adult")

That line means:

Text is this: if age < 18 then “Minor” else “Adult”

That line is used in this subroutine:

Dim age

age = InputBox("How old are you?")

Text = IIf(age < 18, "Minor”, "Adult")

The abbreviation IIf means “Immediate If”. It lets you do an If immediately, without have to type the words “Then” and “Else”.

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:

Dim response

response = InputBox("Do you love me?")

If response = "yes" Then

    MsgBox("I love you too!")

Else

    MsgBox("I don't love you either!")

End If

End

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” or “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:

If MsgBox("Do you love me?", vbYesNo) = vbYes Then

    MsgBox("I love you too!")

Else

    MsgBox("I don't love you either!")

End If

End

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 say “I love you too!” If the human does otherwise (by clicking the No button), the computer says “I don’t love you either!”

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).


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:

Dim feeling

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

    MsgBox("That's good!")

ElseIf feeling = "lousy" Then

    MsgBox("Too bad!")

Else

    MsgBox("I feel the same way!")

End If

Then end the whole program:

End

Instead of typing that multi-line If, you can type this
Select statement instead, which is briefer and simpler:

Select Case feeling

    Case "fine"

        MsgBox("That's good!")

    Case "lousy"

        MsgBox("Too bad!")

    Case Else

        MsgBox("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”,

                  say “That’s good!”

         In the case where the feeling is “lousy”,

                  say “Too bad!”

         In the case where the feeling is anything else,

                  say “I feel the same way!”

While you’re typing the Select statement, the computer automatically indents the lines for you and automatically types “End Select” underneath.


Complete subroutine Here’s a complete subroutine:

Dim feeling

feeling = InputBox("How are you?")

Select Case feeling

    Case "fine"

        MsgBox("That's good!")

    Case "lousy"

        MsgBox("Too bad!")

    Case Else

        MsgBox("I feel the same way!")

End Select

MsgBox("I hope you enjoyed your therapy. Now you owe $50.")

End

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 MsgBox line always makes the computer end the conversation by saying:

I hope you enjoyed your therapy. Now you owe $50.

In that program, try changing the strings to make the computer say 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

When typing a Case statement, don’t bother typing the word “Is”. The computer will type it for you automatically.

Exit Sub

To make the computer skip the bottom part of your subroutine, say Exit Sub, like this:

MsgBox("I love the company president")

Exit Sub

MsgBox("I love him as much as stale bread")

When you run that program (by clicking “Start”), the computer will say “I love the company president” but then exit from the subroutine, without saying “I love him as much as stale bread”. The computer will say just:

I love the company president

Suppose you write a subroutine that displays many messages, and you want to run the program several times (so several of your friends see the messages). If one of your friends would be offended by the last few messages, send that friend an abridged subroutine! Here’s how: put Exit Sub above program part that you want the computer to ignore.

“Exit Sub” versus “End”. Instead of saying “Exit Sub”, you can say “End”. Here’s the difference:

When the computer encounters “Exit Sub” in a subroutine, the computer stops running that subroutine but continues running the rest of the program: for example, it displays Form1, until the human clicks Form1’s X button.

When the computer encounters “End” in a subroutine, the computer stops running the whole program and automatically clicks Form1’s X button.


Property list

While you’re creating or editing a Visual Basic program, you see tabs near the screen’s top-left corner. Try clicking those tabs now:

If you click the “Form1.vb [Design]” tab, you see the Form1 window itself, so you can admire the Form1 window’s size, color, and any writing in it.

If you typed a subroutine for Form1, you also see a “Form1.vb” tab. If you click that tab, you see the subroutine you typed.

Try this experiment.…

Click the “Form1.vb [Design]” tab, so you see the Form1 window itself. Then click (just once) in the middle of the Form1 window.

Then the screen’s bottom-right corner should show a list, whose title is:

Properties

Form1 System.Windows.Forms.Form

If you don’t see that list yet, press the F4 key (or click View then then Properties Window) then try again to click in the middle of the Form1 window.

That list is called Form1’s main property list (or properties window). It’s divided into these 9 categories:

Accessibility

Appearance

Behavior

Data

Design

Focus

Layout

Misc

Window Style


Here’s the full list:

Property                      Value

Accessibility

AccessibleDescription

AccessibleName

AccessibleRole             Default

Appearance

BackColor                     Control

BackgroundImage       (none)

BackgroundImageLayout   Tile

Cursor                           Default

Font                               Microsoft Sans Serif, 7.8pt

ForeColor                       ControlText

FormBorderStyle          Sizable

RightToLeft                   No

RightToLeftLayout       False

Text                                Form1

UseWaitCursor             False

Behavior

AllowDrop                    False

AutoValidate                 EnablePreventFocusChange

ContextMenuStrip        (none)

DoubleBuffered            False

Enabled                         True

ImeMode                      NoControl

Data

(ApplicationSettings)

(DataBindings)

Tag

Design

(Name)                          Form1

Language                      (Default)

Localizable                   False

Locked                          False

Focus

CausesValidation          True

Layout

AutoScaleMode             Font

AutoScroll                     False

AutoScrollMargin          0, 0

AutoScrollMinSize        0, 0

AutoSize                        False

AutoSizeMode              GrowOnly

Location                        0, 0

MaximumSize                0, 0

MinimumSize                 0, 0

Padding                        0, 0, 0, 0

Size                                300, 300

StartPosition                 WindowsDefaultLocation

WindowState                Normal

Misc

AcceptButton                (none)

CancelButton                (none)

KeyPreview                   False

Window Style

ControlBox                   True

HelpButton                   False

Icon                               (Icon)

IsMdiContainer             False

MainMenuStrip             (none)

MaximizeBox                 True

MinimizeBox                 True

Opacity                          100%

ShowIcon                      True

ShowInTaskbar             True

SizeGripStyle                Auto

TopMost                       False

TransparencyKey

(The screen shows part of the list. To see the whole list, use the list’s scroll arrows.)

Text

The top of Form1’s window normally says “Form1”. That’s called the window’s title (or caption or text). Instead of making the title say “Form1”, you can make it say “Results” or “Payroll results” or “Mary’s window” or “Fun stuff” or “Hey, I’m a funny window” or anything else you wish!

To make Form1’s title say “Fun stuff”, you can put this line in Form1’s subroutine —

        Text = "Fun stuff"

but here’s an easier way:

In Form1’s main property list, click the word “Text” (which is in the Appearance category, after you scroll up or down to see it), then type what you want the title to be, so the property list’s Text line becomes this:

Text                               Fun stuff

When you finish typing, press the Enter key.

Try that now! It makes the top of Form1 say “Fun stuff” immediately (or when you press Enter or click “Start” or the Form1 window or the “Form1.vb [Design]” tab).

Color

Normally, the Form1 window’s middle is a big blank area that’s nearly white (a color called Control, which is very light gray). To make it red instead, you can put this line in Form1’s subroutine —

        BackColor = Color.Red

but here’s an easier way:

In Form1’s main property list, click BackColor (which is in the Appearance category) then BackColor’s down-arrow then a color category (“Custom” or “Web” or “System”) then the color you want (such as Red, which you’ll see in the Web category, after you scroll down).

Try that now! It makes Form1’s background color become Red instantly.

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 clicked “Start”), 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 = 2

Property-list method In Form1’s main property list, click WindowState (which is in the Layout category) then WindowState’s down-arrow then Maximized. That makes the property list’s WindowState line become:

WindowState                Maximized

When you run the program (by clicking “Start”), Form1’s window will be maximized.

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 Form1’s main property list, click MaximizeBox (in the Windows Style category) then press the F key (which means “False”). That makes the property list’s MaximizeBox line become:

MaximizeBox                False

That make Form1’s maximize button (which is also called the maximize box) be grayed out while the program runs; the maximize button will become gray instead of black-and-white. That grayed-out button will ignore all attempts to be clicked, so the window will refuse to maximize.

Resize

Normally, Form1 is 300 pixels wide and 300 pixels tall. Here’s how to adjust that size.…

Property-list method In Form1’s main property list, click Size (in the Layout category), then change “300, 300” to the size you wish, by editing those numbers. For example, if you want Form1 to be 500 pixels wide and 400 pixels tall, change the size to “500, 400”. The first number is the form’s width; the second number is the form’s height.

The biggest permissible size is the size of your whole screen, plus a few pixels more. For example, if your screen is Full HD (which is 1080p and has a resolution of 1920-by-1080), the biggest permissible size for you is “1924, 1084”. If you want Form1 to be half as wide and half as tall as the full screen, choose “960, 540”.

For a Full HD screen, the smallest permissible size is “166, 47”. That’s barely enough to show Form1’s fundamental buttons (close, maximize, and minimize), not much else!

If you request a size that’s very big (almost as big as the screen), Form1 won’t look that big until you run the program (by clicking “Start”).

Drag method While the program is running (because you clicked “Start”), 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.)

Click the “Form1.vb [Design]” tab (so you see what Form1 looks like, not subroutines you typed).

At Form1’s bottom right corner, you see a tiny white 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). You’ll see that size in the property list’s Size line (in the Layout category).

Refuse to resize

In Form1’s main property list, the Appearance category’s FormBorderStyle line normally says:

FormBorderStyle       Sizable

Try this experiment: click FormBorderStyle then FormBorderStyle’s down-arrow then “FixedToolWindow”, so the line becomes:

FormBorderStyle       FixedToolWindow

That prevents stupid humans from changing Form1’s size. When a human runs the program (by clicking “Start”), Form1’s window will have no maximize button, no restore-down button, no minimize button, and no resizable edges. Form1 stays the size you specified in the property list (such as the property list’s Size line), so stupid humans can’t mess up your beautiful design (unless they edit your subroutine or property list).

Form position

Here’s how to adjust Form1’s position.…

Property-list method In Form1’s main property list, click the Layout category’s StartPosition then StartPosition’s down-arrow. You see this list of choices:

Manual

Center Screen

WindowsDefaultLocation

WindowsDefaultBounds

CenterParent

Click a choice now. You’ll see the effect later (when you click “Start” to run the program).

The computer assumes you want “WindowsDefaultLocation” unless you click a different choice instead.

“WindowsDefaultLocation” puts Form1 near the screen’s top-left corner (leaving a 1¾-inch margin gap) and makes Form1’s size be what you chose in the Size line.

“CenterScreen” puts Form1 at the screen’s center and makes Form1’s size be what you chose in the Size line.

“CenterParent” puts Form1 at the center of what Windows thinks is appropriate (which is typically left of the screen’s center) and makes Form1’s size be what you chose in the Size line.

“WindowsDefaultBounds” puts Form1 very near the screen’s top-left corner (leaving just a ½-inch margin gap) and makes Form1 be big (9¼ inches wide, 6½ inches tall). The Size line is ignored.

“Manual” puts Form1 at the screen’s top-left corner (leaving no gap, unless you change the Location line to something different from “0, 0”) and makes Form1’s size be what you chose in the Size line.

All those inch measurements are approximate and depend on your screen’s size.

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.

Opacity

Normally, Form1 is completely opaque: while the program is running, Form1 completely blocks the view of anything behind it.

To have fun, reduce Form1’s opacity: in Form1’s main property list, click the Windows Style category’s Opacity, then change “100%” to “75%”. When you run the program (by clicking “Start”), Form1 will be just partly opaque; it will be partly transparent, so you can see, faintly, what’s behind the form.

If you make the opacity even lower — 50% or 25% — Form1 will be hardly opaque at all — it will be very transparent — so you can easily see what’s behind it, as if Form1 were just a ghost.

Don’t make the opacity be 0%. That would make Form1 completely invisible, so you couldn’t see it at all, couldn’t click its close box, and couldn’t stop the program!

Don’t make the opacity be less than 25%. That would make Form1 difficult to see.

Try making the opacity be 90%.

Opacity doesn’t work well if your Windows version is old (Windows XP) or stripped-down (Windows Vista Basic or Windows 7 Starter), since those Windows versions lack Windows Aero (which makes windows partly transparent).


Toolbox

You’ve learned how to create and manipulate an object called “Form1”. You can create other objects also, by using the toolbox.

See the toolbox

Click the “Form1.vb [Design]” tab then “View” (which is near the screen’s top-left corner) then “Toolbox”. Then you see 10 toolbox categories:

All Windows Forms

Common Controls

Containers

Menus & Toolbars

Data

Components

Printing

Dialogs

WPF Interoperability

General

(If you don’t see that whole list yet, scroll down.)

See common controls

Click “Common Controls” once or twice, until you see this list indented under “Common Controls”:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


To the right of the word “Toolbox”, you see an X. Left of the X you see a pushpin. If the pushpin is still horizontal,
make it vertical by clicking it. That makes the toolbox stay on the screen nicely (perminantly and left of your other work).

Each object in the toolbox is called a tool.

Button

Try this experiment. Double-click the Button tool. That makes a button appear in Form1’s middle, near Form1’s top-left corner (or near a previous button). The button is a rectangle and says “Button1” on it.

(If you wish, 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, just leave the button where the computer put it.)

The button says “Button1” on it. Just for fun, let’s make it say “Click me” instead. To do that, click Text (in the property list) and type “Click me”, so the property list’s Text line becomes:

Text                            Click me

That makes the button’s text become “Click me” (instead of “Button1”).

Notice that the property list concerns the button and its text (instead of Form1’s text), because the button is highlighted.

Let’s write a program so if a human clicks the button (which says “Click me”), Form1 will say “Thanks for the click”. To do that, double-click the button. The double-clicking tells the computer you want to write a subroutine about that object (the button).

The computer starts writing the subroutine for you. The computer writes:

Public Class Form1

    Private Sub Button1_Click…

 

    End Sub

End Class

Insert this line in the middle of the subroutine —

        Text = "Thanks for the click"

so the subroutine looks like this:

Public Class Form1

    Private Sub Button1_Click…

        Text = "Thanks for the click"

    End Sub

End Class

That subroutine tells the computer that when Button1 is clicked, the computer should say “Thanks for the click” on Form1.

Try it: run that program (by clicking “Start”). You’ll see Form1 with a button on it that says “Click me”. If you click the button, the subroutine makes Form1 say “Thanks for the click” (after you maximize Form1 so you can see all that).

In that subroutine, the computer assumes you want the text “Thanks for the click” to be on Form1, not on the button. If you want that text to be on the button instead, say Button 1’s Text instead of just Text. To say Button 1’s Text, type Button1.Text, so the subroutine looks like this:

Public Class Form1

    Private Sub Button1_Click…

        Button1.Text = "Thanks for the click"

    End Sub

End Class

But to fit “Thanks for the click” onto the button, you must widen the button, by doing this:

If the program is still running, finish running it (by clicking Form1’s X button). Then click the “Form1.vb [Design]” tab, so you see Form1 and can modify the appearance of Form1 (and of its button). Then widen the button (by dragging the button’s handles).

Two buttons Let’s write a program that has two 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:

If a previous program is still running, finish running it (by clicking Form1’s X button). If you’re not in Visual Basic, go into it.

Click “New Project” or the New Project button (which is near the screen’s top-left corner, below the word “File”). Click “Windows Forms Application”, type a name in the Name box, and press Enter, so you see the Form1 window.

You should also see the Toolbox. (If you don’t see it yet, continue following the “See the toolbox” instructions on the previous page.)


In the Toolbox, double-click the Button tool. A command button appears in Form1 and is called Button1. In the property list, click Text then type “Click here for red” (and press Enter), so the property list’s Text line becomes:

Text                                                Click here for red

That tries to make the button’s text become “Click here for red”. To fit all that text onto the button, widen the button (by dragging one of its handles).

In the Toolbox, double-click the Button tool again. That makes another command button appear in Form1 and be called Button2. Unfortunately, the Button2 button covers up the Button1 button, so you can’t see the Button1 button. Drag the Button2 button out of the way (toward the right), so you can see both buttons side-by-side.

The Button2 button should be highlighted. (If it’s not highlighted, click it to make it highlighted.) In its property list, change its Text from “Button2” to “Click here for blue” (by clicking Text then typing “Click here for blue” and pressing Enter). Widen the Button2 button (by dragging one of its handles) so it shows all of “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 Button1_Click…

        BackColor = Color.Red

    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 the “Form1.vb [Design]” tab), so you can see Form1.

Double-click the “Click here for blue” button, and write this subroutine for it:

    Private Sub Button 2_Click…

        BackColor = Color.Blue

    End Sub

While you’re writing that subroutine, you’ll see the other subroutine above it. Altogether, you see:

Public Class Form1

    Private Sub Button1_Click…

        BackColor = Color.Red

    End Sub

 

    Private Sub Button 2_Click…

        BackColor = Color.Blue

    End Sub

End Class

Then run the program by clicking “Start”. 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 buttons A good habit is to put buttons side-by-side, in Form1’s bottom right corner. That way, the buttons won’t interfere with 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 button called “Exit”, so that clicking it will make the computer exit from the program.

To do that, create an ordinary button; but make the button’s text say “Exit” (or anything else you prefer, such as “Quit” or “End” or “Abort” or “Close” or “Click here to end the program”), and make the button’s subroutine say End, like this:

    Private Sub Button3_Click…

        End

    End Sub

Put that Exit button in Form1’s bottom-right corner.

Check box

A check box is a small gray square, with text to the right of the square. At first, the gray square has nothing inside it: it’s empty. While the program runs, clicking the square makes a green check mark (a) appear in the square. If you click the square again, the check mark disappears.

To create a check box, double-click the CheckBox tool. That makes a check box appears in Form1. Drag the check box wherever you wish.

The first check box’s text is temporarily “CheckBox1”; to change that text, click Text (in the property list) and type whatever text you wish. At the end of your typing, press Enter. Suggestion: if you want to type a lot of text, do this instead:

Click Text’s down-arrow. You’ll see a big box to type in. Press Enter at the end of each line you type. When you’ve finished typing all text you want, do this: while holding down the Ctrl key, tap the Enter key.

If you want the computer to react immediately to whether the check box is checked, give the check box this subroutine:

    Private Sub CheckBox1_CheckedChanged…

        If CheckBox1.Checked Then

            type here what to do if CheckBox1 just became checked

        Else

            type here what to do if CheckBox1 just became unchecked

        End If

    End Sub

Dressed example For example, this subroutine makes the computer say “I am dressed” if the check box just became checked but say “I am naked” if the check box just became empty:

    Private Sub CheckBox1_CheckedChanged…

        If CheckBox1.Checked Then

            Text = "I am dressed"

        Else

            Text = "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 say “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 say “I am naked”. Clicking the check box again makes the a reappear and makes the computer say “I am dressed”.

Here’s how to type that subroutine fast:

Type the word “if”, then a space, then the letters “che”. You see a list of computer words that begin with the letter “Che”. In that list, double-click “CheckBox1”. That makes the computer type “CheckBox1” for you.

Type a period. You see a list of computer words; from that list, choose “Checked” by double-clicking it (or if “Checked” was highlighted already, you can choose it by pressing the Tab key).

Multiple check boxes 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.

Although you can put buttons and check boxes wherever you wish, it’s customary to arrange buttons horizontally (so the second button is to the right of the first) but arrange check boxes vertically (so the second check box is below the first). The check boxes (and their texts) form a vertical list of choices.

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 check boxes have no subroutines. Instead, create an OK button in Form1’s bottom-right corner (by creating a button there and making its text be “OK”), then make the OK button’s subroutine look like this:

    Private Sub Button1_Click…

        If CheckBox1.Checked Then

            type here what to do if CheckBox1 is checked

        Else

            type here what to do if CheckBox1 is unchecked

        End If

        If CheckBox2.Checked Then

            type here what to do if CheckBox2 is checked

        Else

            type here what to do if CheckBox2 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 a program that alters Form1’s appearance, to make it red or maximized or red maximized or return to normal. Here’s how to do all that:

Create a check box (called CheckBox1) with title “Red”.

Create a check box (called CheckBox2) with title “maximized”.

Create a command button (called Button1) with title “OK” and this subroutine:

    Private Sub Button1_Click…

        If CheckBox1.Checked Then

            BackColor = Color.Red

        Else

            BackColor = Color.WhiteSmoke

        End If

        If CheckBox2.Checked Then

            WindowState = 2

        Else

            WindowState = 0

        End If

End Sub

Radio button

A radio button resembles a check box but looks and acts like the button on an old-fashioned radio, because of these differences:

To create a check box, double-click the CheckBox tool.

To create a radio button, double-click the RadioButton tool.

A check box is a tiny gray square.

A radio button is a tiny gray circle.

While the program is running,

clicking a checkbox makes a green checkmark appear in the square.

Clicking a radio button makes a blue dot appear in the circle.

Green checkmarks can appear in many checkboxes, simultaneously.

You see just one blue dot. When you click a radio button, the blue dot hops to that radio button and leaves the previous button.

Like checkboxes, radio buttons are arranged vertically (so the second radio button is below the first). The radio buttons (and their titles) form a vertical list of choices.

When the human starts running your program, the first radio button (which is RadioButton1) has a blue dot inside the gray circle, and the computer automatically does RadioButton1’s subroutine (even if the human hasn’t clicked RadioButton1’s button yet).


Afterwards, if the human clicks a different radio button, here’s what happens:

The blue dot hops to that radio button. The computer does that button’s subroutine; but before doing so, the computer does the previous button’s subroutine one more time so it can display a message such as “Sorry to hear you don’t like this choice anymore”.

If you want the computer to react immediately to whether the radio button has the blue dot, give the radio button this subroutine:

    Private Sub RadioButton1_CheckedChanged…

        If RadioButton1.Checked Then

            type here what to do if RadioButton1 just got the blue dot

        Else

            type here what to do if RadioButton1 just lost the blue dot

        End If

    End Sub

3-color example For example, let’s write a program that has 3 radio buttons, labeled “Red”, “Blue”, and “Green”. While the program is running, if the human switches from “Red” to “Blue” (by clicking “Blue” after having clicked “Red”), let’s make the program say “Sorry you don’t like red anymore” and make Form1 become blue. Let’s make the program act similarly for switching between other pairs of colors.

To do that, maximize Form 1 (by making its WindowState property be Maximized) and create the 3 radio buttons (labeled “Red”, “Blue”, and “Green”). Then give the “Red” button (which is RadioButton1) this subroutine:

    Private Sub RadioButton1_CheckedChanged…

        If RadioButton1.Checked Then

            BackColor = Color.Red

        Else

            Text = "Sorry you don’t like red anymore"

        End If

    End Sub

That subroutine runs just when the human changes the Red radio button’s appearance (by clicking it or unclicking it):

When that radio button’s appearance changes to “checked” (contains a blue dot), that subroutine makes Form1 be red.

When that radio button’s appearance changes to “unchecked” (no blue dot), that subroutine makes Form1 say “Sorry you don’t like red anymore”.

Here’s how to type that subroutine fast:

Type the word “if”, then a space, then the letter “r”. You see a list of computer words that begin with the letter R. In that list, double-click “RadioButton1”. That makes the computer type “RadioButton1” for you.

Type a period. You see a list of computer words; from that list, choose “Checked” by double-clicking it (or if “Checked” was highlighted already, you can choose it by pressing the Tab key).

To type the rest of the subroutine fast, keep choosing from lists.

To finish the program, type this subroutine for the “Blue” button (which is RadioButton2) —

    Private Sub RadioButton2_CheckedChanged…

        If RadioButton2.Checked Then

            BackColor = Color.Blue

        Else

            Text = "Sorry you don’t like blue anymore"

        End If

    End Sub

and this subroutine for the “Green” button (which is RadioButton3):

    Private Sub RadioButton3_CheckedChanged…

        If RadioButton3.Checked Then

            Text = "Welcome to New York"

        Else

            MsgBox("You’ve left New York")

        End If

    End Sub

3-city example For a similar example, let’s write an airplane program that has 3 radio buttons, labeled “Los Angeles”, “Dallas”, and “New York”. While the program is running, if the human switches from “Los Angeles” to “Dallas” (by clicking “Dallas” after having clicked “Los Angeles”), let’s make the program say “You’ve left Los Angeles” and “Welcome to Dallas”. Let’s make the program act similarly for traveling between the other cities.

To do that, create the 3 radio buttons (labeled “Los Angeles”, “Dallas”, and “New York”). Then give the “Los Angeles” button (which is RadioButton1) this subroutine:

    Private Sub RadioButton1_CheckedChanged…

        If RadioButton1.Checked Then

            Text = "Welcome to Los Angeles"

        Else

            MsgBox("You’ve left Los Angeles")

        End If

    End Sub

That subroutine runs just when the human changes the Los Angeles radio button’s appearance (by clicking it or unclicking it):

When that radio button’s appearance changes to “checked” (contains a blue dot), that subroutine makes the computer say “Welcome to Los Angeles”.

When that radio button’s appearance changes to “unchecked” (no blue dot), that subroutine makes the computer say “You’ve left Los Angeles”.

To finish the program, type this subroutine for the “Dallas” button (which is RadioButton2) —

    Private Sub RadioButton2_CheckedChanged…

        If RadioButton2.Checked Then

            Text = "Welcome to Dallas"

        Else

            MsgBox("You’ve left Dallas")

        End If

    End Sub

and this subroutine for the “New York” button (which is RadioButton3):

    Private Sub RadioButton3_CheckedChanged…

        If RadioButton3.Checked Then

            Text = "Welcome to New York"

        Else

            MsgBox("You’ve left New York")

        End If

    End Sub

OK button When the human clicks a radio 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 a general OK button, which confirms the human’s desires.

To do that, make the radio buttons have no subroutines, so nothing will happen when those buttons are clicked. In Form1’s bottom-right corner, create an ordinary button whose text says “OK” and whose subroutine looks like this:

    Private Sub Button1_Click…

        If RadioButton1.Checked Then

            type here what to do if RadioButton1 just got the blue dot

        ElseIf RadioButton2.Checked Then

            type here what to do if RadioButton2 just got the blue dot

        ElseIf RadioButton3.Checked Then

            type here what to do if RadioButton3 just got the blue dot

        ElseIf RadioButton4.Checked Then

            type here what to do if RadioButton4 just got the blue dot

        Else

            type here what to do if bottom radio button got blue dot

        End If

    End Sub

That subroutine says: when the OK button is clicked, notice which radio button was clicked and react appropriately.

Label

Form1 has two main parts. One part is a blue bar across Form1’s top: it includes Form1’s minimize button, maximize button, close button, and text. The other part (Form1’s middle) is a big light-gray box: it includes objects you created, such as ordinary buttons, check boxes, and radio buttons.

In Form1’s middle, let’s type this text:

I love you

To do that, double-click the Label tool. That makes the word “Label1” appear in Form1’s middle. Drag “Label1” to the spot in Form1 where you wish to begin typing. To change “Label1” to “I love you”, click Text (in Label1’s property list) then type “I love you”, so the property list says:

Text                                                   I love you

At the end of that typing, press Enter. Then “Label1” becomes “I love you”, so “I love you” is in Form1’s middle.

Multi-line text Instead of making Form1’s middle say just “I love you”, let’s make it say:

I love you

You turned me on

Let’s get married

Here’s how:

After you’ve created a label (by double-clicking the Label tool) and clicked Text, click Text’s down-arrow. You’ll see a big box to type in. Press Enter at the end of each line you type. When you’ve finished typing all text you want, do this: while holding down the Ctrl key, tap the Enter key.

Text equation Here’s a different way to make Form1’s middle say “I love you”.

Create a label (by double-clicking the Label tool). Tell the computer you want to write a subroutine for Form1 (by double-clicking in Form1 but not in the label). Put this line in Form1’s subroutine:

        Label1.Text = "I love you"

That means: the label’s text is “I love you.” That line makes Form1’s subroutine become this:

    Private Sub Form1_Load…

        Label1.Text = "I love you"

    End Sub

When you run the program (by clicking “Start”), the computer will run that subroutine and make Form1’s middle say:

I love you

If instead you want the Form1’s middle to say —

I love you

You turned me on

change the Text line to this:

Label1.Text = "I love you" & Chr(13) & "You turned me on"

That makes the computer type “I love you” then press key #13 (which is the Enter key) then type “You turned me on”. Instead of that long Text line, you can give this pair of shorter Text lines:

Label1.Text = "I love you"

Label1.Text &= Chr(13) & “You turned me on"

In that pair of lines, the first line makes the Text be “I love you”; the next line changes the Text to become all that, combined with Chr(13) and “You turned me on”.

Math Let’s make Form1’s middle say the answer to 4 + 2.

To do that, create a label (by double-clicking the Label tool). Tell the computer you want to write a subroutine for Form1 (by double-clicking in Form1 but not in the label). Put this line in Form1’s subroutine:

        Label1.Text = 4 + 2


That line means: Label1’s text is the answer to 4 + 2. That line makes Form1’s subroutine become this:

    Private Sub Form1_Load…

        Label1.Text = 4 + 2

    End Sub

When you run the program (by clicking “Start”), the computer will run that subroutine and write the answer (6) in Form1’s middle.

To make Form1’s middle say the answer to 4 + 2 and, on the next line, say the answer to 48 + 3, you can put this line in Form1’s subroutine —

        Label1.Text = 4 + 2 & Chr(13) & 48 + 3

or give this pair of lines instead:

        Label1.Text = 4 + 2

        Label1.Text &= Chr(13) & 48 + 3

In that pair of lines, the first line makes the Text be the answer to 4 + 2; the next line changes the Text to become all that, combined with Chr(13) and the answer to 48 + 3.

List box

A list box is a big white box that contains a list of choices, such as these color choices —

Red

Blue

Green

or these country choices —

United States

Canada

Mexico

The list can be short (2 or 3 choices) or tall (hundreds of choices). If the list is too tall 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 ListBox 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 ListBox1. Inside that list box, you temporarily see the word “ListBox1”, but you should put your own list of choices there instead, by using this method —

In the list box’s property list, click “Items” then “…” Type the list of choices, such as:

United States

Canada

Mexico

To do that, press Enter at the end of each line. When you’ve finished typing the whole list, click “OK”.

or this alternate method:

Click the list box’s right-arrow (which is near the box’s top-right corner) then “Edit Items”. Type the list of choices, such as:

United States

Canada

Mexico

To do that, press Enter at the end of each line. When you’ve finished typing the whole list, click “OK” then click in the list box.

Then on Form1, you see the list box containing your choices.

By dragging the box’s handles, try to make the box just tall enough to hold all the choices. (If it isn’t tall enough, the computer automatically adds scroll arrows so humans can scroll through the list while the program runs.)

By dragging the box’s handles, make the box just wide enough to hold the widest choice.

Select one You can give List1 this kind of subroutine:

    Private Sub ListBox1_SelectedIndexChanged…

        Select Case ListBox1.SelectedItem

            Case "United States"

                type here what to do if “United States” is clicked

            Case "Canada"

                type here what to do if “Canada” is clicked

            Case "Mexico"

                type here what to do if “Mexico” is clicked

        End Select

    End Sub

Here’s a shorter way to type the subroutine:

    Private Sub ListBox1_SelectedIndexChanged…

        Select Case ListBox1.SelectedIndex

            Case 0

                type here what to do if the list’s top item (“United States”) is clicked

            Case 1

                type here what to do if the list’s next item (“Canada”) is clicked

            Case 2

                type here what to do if the list’s next item (“Mexico”) is 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 ListBox1 no subroutine, but give the OK button this kind of subroutine —

    Private Sub Button1_Click…

        Select Case ListBox1.SelectedItem

            Case "United States"

                type here what to do if “United States” is clicked

            Case "Canada"

                type here what to do if “Canada” is clicked

            Case "Mexico"

                type here what to do if “Mexico” is clicked

        End Select

    End Sub

or this subroutine:

    Private Sub Button1_Click…

        Select Case ListBox1.SelectedIndex

            Case 0

                type here what to do if the list’s top item (“United States”) is clicked

            Case 1

                type here what to do if the list’s next item (“Canada”) is clicked

            Case 2

                type here what to do if the list’s next item (“Mexico”) is clicked

        End Select

    End Sub

Select multi If you want to let the human select several items from the list (instead of just one item), do this:

In ListBox1’s property list, click SelectionMode then SelectionMode’s down-arrow.

Click either “MultiSimple” or “MultiExtended”. (If you choose “MultiSimple”, the human can select several items by clicking them, and deselect an item by clicking that item again. If you choose “MulitExtended”, 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 (an ordinary button whose caption is “OK”).

Give ListBox1 no subroutine, but give the OK button this kind of subroutine:

If ListBox1.GetSelected(0) Then type here what to do if the list’s top item (“United States”) clicked

If ListBox1.GetSelected(1) Then type here what to do if the list’s next item (“Canada”) clicked

If ListBox1.GetSelected(2) Then type here what to do if the list’s next item (“Mexico”) clicked


Label Next to your list box, you should put some text, explaining the list box’s purpose to the human. To put the text there, create a label with that text (by double-clicking the Label tool), and drag the label until it’s next to your list box.

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 over the size or position of its objects (the window, message, white response box, and OK button).

To be more professional, get control by creating a text box instead. Here’s how.

Double-click the TextBox 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.

Above the box (or left of it), put a label (by double-clicking the Label tool). Make the label contain a message (such as “What is your name?”).

Below the box (or right of the box), create an OK button (a button whose text says “OK”). Make the OK button’s subroutine include these lines —

        Dim x

        x = TextBox1.Text

and anything else you want the computer to do, such as:

        MsgBox("I love " & 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 The typical text box holds just one line of text. To let your text box handle several lines of text well, make 3 adjustments:

In the text box’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 the text box’s property list, click ScrollBars then press the V key (which stands for 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.

Rich-text box

Instead of double-clicking the TextBox tool, try double-clicking the RichTextBox tool. It creates a text box that’s already tall, MultiLine (so the human can type many lines of text in the box), with a vertical scroll bar (which appears when the human types more lines than can fit in the box) and the ability to handle formatted text (which is called rich text). That box is called RichTextBox1.

For best results, make the box even taller and wider (by dragging its bottom-right corner).

In that box, the human can type a number, or a word, or a sentence, or a paragraph, or several paragraphs (by pressing the Enter key at the end of each paragraph), or a whole essay! What the human types in that box is called a document.

For example, if you want to invent your own word-processing program, the first step is to create a rich-text box for the human to type the words into.

Improve the rich-text box Here are 2 popular ways to improve how a rich-text box works:

In RichTextBox1’s property list (at the screen’s bottom-right corner), click “EnableAutoDragDrop” then press the T key. That makes EnableAutoDragDrop be True. Then whenever the human is typing the document, the human can highlight a phrase and drag it to a different spot in the document.

Click RichTextBox1’s right-arrow (which is near the box’s top-right corner) then “Dock in parent container”. That makes RichTextBox1 expand and consume all of Form1. Then while the program is running, if the human changes Form1’s size (by maximizing Form1 or by dragging Form1’s bottom-right corner), RichTextBox1 will change size automatically, to still fill Form1.

Number box

To make the computer wait for the human’s response, you learned you can create a text box (by double-clicking the TextBox tool) and an OK button whose subroutine includes these lines:

        Dim x

        x = TextBox1.Text

If you want to force the human to type a number instead of words, create a number box instead of a text box. Here are the details.…

Double-click the NumericUpDown tool. That creates a number box (a white box in which the human can type a number). Drag it wherever you wish. Adjust its width by dragging its handles.

Above the box (or left of it), put a label (by double-clicking the Label tool). Make the label contain a message (such as “How many children do you have?”).

Below the box (or right of the box), create an OK button (a button whose text says “OK”). Make the OK button’s subroutine include these lines —

        Dim x

        x = NumericUpDown1.Value

and anything else you want the computer to do, such as:

        MsgBox("I'm glad you have " & x)

When the human runs the program, the human sees the number box. That box temporarily has 0 in it, but the human can change that number by retyping it or by clicking the box’s up-arrow (which increases the number) or down-arrow (which decreases the number). When the human has changed the number to what the human wishes, the human clicks the OK button, whose subroutine makes x become the human’s number.

Alter the box’s properties Normally, the number box refuses to let the human say any number over 100. If you want it to permit numbers up to 500, make its property list’s Maximum line say 500. If you want it to permit just numbers up to 20, make its Maximum line say just 20. If you want to encourage the human to type a number that’s small, make the box be narrow (by adjusting its handles).

Normally, the number box refuses to let the human say any number below 0. If you want it to permit numbers down to minus 500, make the property list’s Minimum line say -500. If you want it to require the number to be at least 3, make its Minimum line say 3.

Normally, the number box refuses to accept decimals. If you want it to permit 2 digits after the decimal point (so the human can type dollars-and-cents), make the property list’s DecimalPlaces line say 2.

The number box normally begins displaying the number 0. If you want it to begin by displaying the number 5 instead, make the property list’s Value line say 5.

By adjusting those properties (Maximum, Minimum, DecimalPlaces, Value, and the box’s width), you can encourage the human to be reasonable.

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 ComboBox 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.

Click the box’s right-arrow (which is near the box’s top-right corner) then “Edit Items”. Type your list of suggested responses, such as:

United States

Canada

Mexico

(Press Enter at the end of each line.) When you’ve finished typing the whole list, click “OK” then click in the combo box.

Above (or left of) the box, put a label (by double-clicking the Label tool). Make the label contain a prompt (an instruction to the human about what to put into the box).

Below (or right of) the box, create an OK button (a command button whose caption is “OK”). Make the OK button’s subroutine include these lines —

        Dim x

        x = ComboBox1.Text

and anything else you want the computer to do, such as:

        MsgBox("I'm glad you said " & x)


Drop-down style In combo box’s property list, click DropDownStyle then DropDownStyle’s down-arrow. You see 3 styles:

Simple

DropDown

DropDown List

Click whichever style you wish. If you don’t choose otherwise, the computer assumes you want “DropDown”. That works as I described: the human can type anything into the box, and the suggestion list appears just if the human clicks the box’s down-arrow.

If you choose “Simple” 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 box tall enough to hold the list.

If you choose “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 box.

Picture box

Here’s how to make Form1 show a picture.

First, enlarge Form1 (by dragging its bottom-right corner), to let it hold a big picture better.

Then double-click the PictureBox tool. That puts a box in Form1’s middle, near Form1’s top-left corner.

Enlarge that box (by dragging its bottom-right corner), to let it hold a big picture better. If you want the box to be smaller than Form1 (so Form1 can hold other objects also), drag the box where you wish (by pointing at the box’s middle, the dragging).

Click the box’s right-arrow (which is near the box’s top-right corner) then “Choose Image” then the bottom “Import” button then “Pictures” (which is on the left). That shows what’s in your hard disk’s Pictures folder.

Double-click the picture you want (after clicking or double-clicking any folders it’s buried in). For example, you can try double-clicking the “Sample Pictures” icon (which Windows has put in your Pictures folder) then “Penguins” (Windows 7’s photo of a penguin trio) or “Annie in the Sink” (Windows Vista’s photo of Annie the cat, sitting in a sink).

You see a bigger view of the picture (or its top-left corner). Click “OK”.

Click the Size Mode box’s down-arrow. You see this menu:

Normal

StretchImage

AutoSize

CenterImage

Zoom

If the picture is bigger than the box, here’s what those choices mean.

Zoom is the safest choice: it shrinks the picture nicely, so it fits in the box’s center.

StretchImage fills the whole box by shrinking (or stretching) the picture, which gets distorted.

CenterImage puts just the picture’s center into the box.

Normal puts just the picture’s top-left corner into the box.

AutoSize stretches the box, to hold as much of the picture as possible.

The computer assumes you want “Normal”. If you prefer a different choice (such as “Zoom”), click it.

Should you dock? If you click “Dock in parent container”, the box will expand to fill Form1. (If you regret that expansion, undo it by clicking “Undock in parent container”.)


 

Add a form

Besides Form1, you can create extra forms, called Form2, Form3, Form4, etc. To create an extra form, click the Add New Item button (which is near the screen’s top, under the words “Edit” and “View”) then double-click the Windows Form icon.

For example, let’s make a 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 blank Form1).

Create Form2, by doing this:

Click the Add New Item button (which is near the screen’s top, under the word “Edit”). Double click the Windows Form icon.

You see Form2. (It covers Form1). Make it say “I love you” (by typing “I love you” in the property list’s Text box and pressing Enter).

Make Form1 reappear (by clicking the “Form1.vb [Design]” tab). On Form1, create a button (by double-clicking the Button tool). Make it say “Click me” (by typing “Click me” in the property list’s Text box and pressing Enter). Double-click that button and type this subroutine line:

        Form2.Visible = True

That means: when the button is clicked, make Form2 suddenly become visible.

When you run the program (by clicking “Start”), you see Form1, which contains a button saying “Click me”. 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).

Web browser

Here’s how to make a form’s middle show a Web page.

Create a blank form. (For a quick, fun experiment, you can use Form1, though in a practical program you’d use another form instead, such as Form2.) Make that blank form be maximized (by making its property list’s WindowState line say “Maximized”) or at least rather big (by making its property list’s Size line have rather big numbers).

Double-click the WebBrowser tool. That makes the form’s entire middle be devoted to the Web and be called WebBrowser1. In WebBrowser1’s property list, click “Url” then type the Web address you want the form to show (such as “www.yahoo.com”).

When you run the program (by clicking “Start”), the form’s middle will show that Web page (or as much of it as will fit in the form’s middle, accompanies by scroll arrows).

Timer

To make the computer pause, use the Timer tool. Here are examples.

I love you!!!!!!!!!! Here’s how to make the computer say “I love you”, then pause, then add an exclamation point (so you see “I love you!”), then pause, then add another exclamation point (so you see “I love you!!”), then keep repeating that process, so you eventually see “I love you!!!!!!!!!!” and beyond!

Make Form1’s Text begin as “I love you” by doing this:

Click in Form1, so the screen’s bottom right corner shows Form1’s main property list. In that list, click “Text” then type “I love you”, so the property list’s Text line becomes this:

Text                                I love you

When you finish typing, press the Enter key. That makes Form1’s title (top) say “I love you”.

The next step is to say “add an exclamation point after pausing”. To deal with pausing, you must use the Timer tool. Here’s how.…

Look at the toolbox (which is at the screen’s left side and shows the tools). Using the toolbox’s scroll-down arrow, scroll down until you see a heading called “Components”.

Left of that heading, you see a triangle. That triangle should be solid black. (If the triangle has a white middle instead, click the triangle to make it solid black.)

Under the heading “Components”, you should see the Timer tool. Double-click it. That puts a Timer1 icon below Form1.

At the screen’s bottom-right corner, you see Timer1’s property list, which looks like this:

Property                      Value

(ApplicationSettings)

(Name)                          Timer1

Enabled                         False

GenerateMember          True

Interval                          100

Modifiers                      Friend

Tag

In that property list, click “Interval” then type 2000, so the Interval line becomes this:

Interval                       2000

That makes each pause be 2000 milliseconds (which is 2000 “thousands of a second”, which is 2 seconds).

In that property list, click “Enabled” then press the T key, so the Enabled line becomes this:

Enabled                         True

That turns the timer on, so it works.

Double-click the Timer1 icon, so you can write Timer1’s subroutine. Type this line in Timer1’s subroutine:

        Text &= "!"

That makes the Text (of Form1) lengthen, by having an extra “!” added. Typing that line makes Timer1’s subroutine become this:

    Private Sub Timer1_Tick…

        Text &= "!"

    End Sub

When you run the program (by clicking “Start”), the computer will show Form1 saying “I love you”, then pause for the next clock tick (the interval between ticks being 2000 milliseconds), then do Timer1’s subroutine (which turns “I love you” into I love you!”), then pause for the next clock tick, then do again Timer1’s subroutine (which turns “I love you!” into “I love you!!”), then pause for the next clock tick, then do again Timer1’s subroutine (which turns “I love you!!” into “I love you!!!”), then keep repeating that process, so you eventually see “I love you!!!!!!!!!!” and beyond. When the exclamation points become too numerous to fit in Form1’s title area, the computer changes the extra exclamation points to “…”. The program keeps running until you stop it (by clicking Form1’s X button).

If you want the exclamation points to come faster, make the interval shorter, by making Timer1’s Interval be less than 2000 milliseconds. For example, try making the Interval be 1000 milliseconds (which is 1 second), or 500 milliseconds (which is half a second), or 1 millisecond (which is almost instantaneous).

If you want the computer to add just one exclamation point and then relax (without adding further exclamation points), make Timer1’s subroutine become this:

    Private Sub Timer1_Tick…

        Text &= "!"

        Timer1.Enabled = False

    End Sub

That subroutine says: when the clock ticks, add an exclamation point to the text but then disable the timer, so no further exclamation points will be added.


 

To play a joke on a human, make Timer1’s Interval be 3000 (so the computer will pause 3 seconds before giving the joke’s punch line) and make Timer1’s subroutine become this:

    Private Sub Timer1_Tick…

        Text &= "r mother!"

        Timer1.Enabled = False

    End Sub

That subroutine says: when the clock ticks (after 3 seconds), make the Text change from “I love you” to “I love your mother!” then disable the timer (because the joke’s timing is done).

Try making Timer1’s subroutine become this instead:

    Private Sub Timer1_Tick…

        Text &= "I'm happy when you’re gone"

    End Sub

That subroutine says: when the clock ticks (after 3 seconds), make the Text change from “I love you” to “I’m happy when you’re gone”.

Count the seconds Here’s how to make Form1 count how many seconds have elapsed, so Form1 begins by saying 0, then a second later says 1, then a second later says 2, etc.

Make Form1’s Text begin at 0 by doing this:

Click in Form1, so the screen’s bottom right corner shows Form1’s main property list. In that list, click “Text”, then type number 0 and press Enter.

In the toolbox (which at the screen’s left side and shows the tools), find the Timer tool (by scrolling down to “Components”, clicking any + sign left of “Components”, then scrolling down further). Double-click that Timer tool. That puts a Timer1 icon below Form1.

In Timer1’s property list (which is at the screen’s bottom-right corner), click “Interval” then type 1000, so you see this line:

Interval                       1000

Click “Enabled” then press the T key, so the Enabled line becomes this:

Enabled                         True

Double-click the Timer1 icon. Type this subroutine for Timer1:

        Text += 1

That increases the text’s number, by adding 1 to it.

When you run the program (by clicking “Start”), Form1’s Text begins as 0 but increases to 1, then 2, then 3, etc.

Tell the date and time Here’s how to make Form1 act as a clock, so it tells you the date and time and updates itself every second!

Create a Timer1 icon (by double-clicking the Timer tool, which is in the toolbox under “Components”). In Timer1’s property list (which is at the screen’s bottom-right corner), make the “Interval” be 1000 and make “Enabled” be True.

Double-click the Timer1 icon. Type this subroutine for Timer1:

        Text = My.Computer.Clock.LocalTime

That makes the text become a message such as this:

12/31/2009 11:59:30 PM

You’ll see such a message when you run the program (by clicking “Start”). Since you set the Interval to 1000 milliseconds (which is 1 second), that text will correct itself every second.


Switch to blue Here’s how to make Form1 begin as red but then, after a pause, become blue.

Make Form1 begin as red by doing this:

Click in Form1, so the screen’s bottom right corner shows Form1’s main property list. In that list, click “BackColor” (which you’ll see after you scroll up) then BackColor’s down-arrow then “Web” then “Red” (which you’ll see after you scroll down).

Create a Timer1 icon (by double-clicking the Timer tool, which is in the toolbox under “Components”). In Timer1’s property list (which is at the screen’s bottom-right corner), make the “Interval” be 2000 and make “Enabled” be True.

Double-click the Timer1 icon. Type this subroutine for Timer1:

        BackColor = Color.Blue

When you run the program (by clicking “Start”), Form1 begins as red but switches to blue (after a delay of 2000 milliseconds, which is 2 seconds).

Let’s make the subroutine fancier, so Form1 keeps alternating between red and blue. We’ll make Form1 start as red, then switch to blue, then switch back to red, then switch back to blue, then switch back to red, etc., forever. To do that, change the subroutine line to this:

        BackColor = IIf(BackColor = Color.Red, Color.Blue, Color.Red)

It says the BackColor becomes this: if the BackColor was Red, then it becomes Blue, else it becomes Red.

Color dialog

Here’s how to let the human pick a color for Form1.

Look at the toolbox (which is at the screen’s left side and shows the tools). Using the toolbox’s scroll-down arrow, scroll down until you see a heading called “Dialogs”.

Left of that heading, you see a square. That square should contain a minus sign. (If it contains a plus sign instead, change the plus sign to a minus sign by clicking it.)

Under the heading “Dialogs”, you should see the ColorDialog tool. Double-click it. That puts a ColorDialog1 icon below Form1 and lets Form1’s subroutine mention “ColorDialog1”.

Double-click Form1. Write this Form1 subroutine:

        ColorDialog1.ShowDialog()

        BackColor = ColorDialog1.Color

When you run the program (by clicking “Start”), the subroutine’s top line makes the computer show the human the color dialog box, which contains 48 colors (plus a feature to let the human invent custom colors). When the human clicks one of the 48 colors (or a custom color) and then clicks “OK”, the subroutine’s bottom line makes Form1’s background color become the color the human chose.

While viewing the color dialog box, here’s how the human can create a custom color:

Click “Define Custom Colors”.

At the color dialog box’s right edge, you see a triangle pointing toward the left. Drag that triangle up, until it’s halfway up the bar it points to.

You see a big, colorful square. Click your favorite color in that square.

Below that square, you see a box marked “Color/Solid”; that shows the color you’ve chosen. Adjust that color, by dragging the triangle up (which makes the color lighter) or dragging the triangle down (which makes the color darker) or clicking a different spot in the big, colorful square.

When you’re satisfied, click “Add to Custom Colors”. That creates a small square for the color. Click that square then “OK”.


 

Helpful hints

Here are some hints to help you master programming.

Stop debugging

While your program is running, you can interrupt it by clicking the Stop Debugging button (which is a red square at the screen’s top center).

The computer refuses to let you edit a program that’s in the middle of running. If you try to edit a program that’s running, the computer gripes by saying —

Changes are not allowed while code is running.

then waits for you to click “OK” (which means you’ve read the gripe).

To edit a program that’s running, stop it first (by clicking Form1’s X or the Stop Debugging button) then try to edit your program.

Avoiding Dim

If x is a variable, you’re supposed to warn the computer by saying:

        Dim x

If you’re too lazy to say “Dim” for each variable, say
Option Explicit Off at your program’s top, so your program looks like this:

Option Explicit Off

Public Class Form1

    Private Sub Form1_Load…

 

    End Sub

End Class

To type “Option Explicit Off” up there, do this:

While holding down the Ctrl key, tap the Home key.

Press the Enter key.

Press the up-arrow key.

Type “Option Explicit Off”.

The “Option Explicit Off” prevents the computer from griping about missing Dim lines. It makes your program’s variables work even if you don’t say “Dim”. But it also prevents the computer from warning you about using variables in ridiculous ways. Say “Option Explicit Off” just if you’re too lazy to say “Dim” — and you’re sure you’re not making ridiculous mistakes about variables.

Apostrophe

In your subroutine, you can type comments to help programmers understand your program. The comments can mention your name, the date you wrote the program, the program’s purpose, the purpose of each variable, special tricks you used, cynical comments, and any other comments you’d like to share with your programming buddies and to remind yourself of how you’ve been thinking.

To type such a comment in your subroutine,
begin the comment with an apostrophe, like this:

        'This subroutine is another dumb example by Russ.

        'It was written on Halloween, under a full moon.

        c = 40 'because Russ has 40 computers

        h = 23 'because 23 of his computers are haunted

        Text = c – h 'That many computers are unhaunted.

When you run the program, the computer ignores everything that’s to the right of an apostrophe. So the computer ignores lines 1 and 2; in lines 3 & 4, the computer ignores the “because…”; in the bottom line, the computer ignores the comment about being unhaunted. Since c is 40, and h is 23, the bottom line makes the computer say:

17

Everything to the right of an apostrophe is called a comment (or remark).

Turning green When you type the subroutine,
the computer makes each apostrophe and comment turn green. Then the computer ignores what’s green.

Temporarily ignore Suppose you’ve written a subroutine but wonder what would happen if one of the lines were deleted. To find out, you could delete the line (by pressing the Delete key repeatedly or using other techniques), then run the shortened program, then put the line back in (by retyping it). But here’s a faster way to do that experiment:

To temporarily make the computer ignore the line, type an apostrophe in front of that line. The apostrophe turns that line into a comment, so the computer ignores the line. Later, when you want to reactivate that line, just delete the apostrophe.

Temporarily deactivating a line (by putting an apostrophe before it so it becomes a comment) is called commenting out the line.

Multiple lines To make several lines become comments, you can type an apostrophe in front of each of those lines; but here’s a faster way: drag across those lines (by using your mouse), then click the Comment-out button (which is near the screen’s top, under “Tools”, and shows two green lines between black lines).

That makes the computer type an apostrophe in front of each of those lines and makes the lines turn green.

Later, when you want to reactivate those lines, drag across them again then click the Uncomment button (which is to the right of the Comment-out button): that removes the apostrophes and makes the lines turn black again.

 

Places for output

You can make the computer show answers in many places. Let’s review the places you saw previously, then explore places that are more exotic.

Top of Form1

You learned that if Form1’s subroutine says —

        Text = 5 + 2

the computer writes the answer, 7, at the top of Form1, where Form1’s title belongs.

Unfortunately, the top of Form1 doesn’t have much space: the answer must be narrow (unless you widened Form1) and the answer must not consume 2 lines.


Pop-up window

If the subroutine says —

        MsgBox(5 + 2)

the computer writes the answer in a
pop-up window that appears suddenly.

If the answer is long, the pop-up window expands automatically, vertically and horizontally, to hold the answer. (To create a 2-line answer, say this where you want the computer to press the Enter key: & Chr(13) &.)

Afterwards, the computer waits for the human to click “OK”.

Middle of Form1

If you’ve created a label (by
double-clicking the Label tool) and your subroutine says —

        Label1.Text = 5 + 2

the computer writes the answer in the middle of Form1, where Label1 is.

If the answer is long, the Label1 area expands automatically, vertically and horizontally, to hold the answer, up to the size of Form1. (To create a 2-line answer, say this where you want the computer to press the Enter key:
& Chr(13) &.)

Output window

If the subroutine says —

        Console.WriteLine(5 + 2)

or —

        Debug.Print(5 + 2)

the computer writes the answer at the screen’s bottom, at the bottom of the output window.

After you admire that answer, stop the program (by clicking Form1’s X button or the Stop Debugging button (which is a red square at the screen’s top center).

Immediate window

To create an immediate window, click “Debug” (which is at the screen’s top) then “Windows” then “Immediate”. Then you see an immediate window at the screen’s bottom.

In that window, type a command such as:

>? 5+2

Type it correctly: begin with the symbol >, then a question mark, then a space, then the computation. When you finish typing that, press the Enter key. The computer immediately types the answer underneath:

7


Console screen

To create a new program normally, you click “Windows Forms Application”.

Instead of clicking “Windows
Forms Application”, try clicking
Console Application”. That tells the computer you want a stripped-down version of Visual Basic, where the computer writes answers on a console screen (which looks like DOS instead of Windows and has no forms or buttons or icons).

When you’ve double-clicked the Console Application icon, you immediately see this stripped-down subroutine:

Module Module1

 

    Sub Main()

 

    End Sub

 

End Module

Click in the middle of that subroutine and say “Console.WriteLine(5 + 2)”, so the subroutine becomes this:

Module Module1

 

    Sub Main()

        Console.WriteLine(5 + 2)

    End Sub

 

End Module

Just above the “End Sub”, say “Do” and “Loop”, like this:

Module Module1

 

    Sub Main()

        Console.WriteLine(5 + 2)

        Do

 

        Loop

    End Sub

 

End Module

When you type the “Do” (and press Enter), the computer automatically types the “Loop” for you.

When you run the program (by clicking “Start”), the computer writes the answer on a console screen, which is a window whose middle looks like DOS. (To create a 2-line answer, give 2 Console.WriteLine commands. At the end of each answer, the computer presses the Enter key, unless you say Write instead of WriteLine.) Your subroutine’s “Do” and “Loop” make the computer pause, so you have time to read the answer.

After you’ve read the answer, close the console screen (by clicking its X button).


Avoiding Do In the subroutine, instead of typing “Do” (and waiting for the computer to type “Loop”), you can type “Console.ReadKey()”, so the subroutine looks like this:

Module Module1

 

    Sub Main()

        Console.WriteLine(5 + 2)

        Console.ReadKey()

    End Sub

 

End Module

The “Console.ReadKey()” makes the computer wait for the human to press a key. When the human presses any key (such as Enter), the computer ends the program and closes the console screen.

Avoiding Console Here’s a shortcut. Instead of typing “Console.” so often (before each WriteLine and Write and ReadKey), just type this line at the subroutine’s top —

Imports System.Console

so the subroutine looks like this:

Imports System.Console

Module Module1

 

    Sub Main()

        WriteLine(5 + 2)

        ReadKey()

    End Sub

 

End Module

Print form

Here’s how to let the human print Form1 onto paper.

Double-click the PrintForm tool, which is in the Visual Basic PowerPacks category (whose tools you can see by clicking the triangle left of “Visual Basic PowerPacks” once or twice). That puts a PrintForm1 icon below Form1 and lets subroutines mention “PrintForm1”.

On Form1, create a button (by double-clicking the Button tool). Make the button’s text say “Print” (by clicking “Text” then typing “Print”). Double-click the button, so you can write the button’s subroutine. Make the button’s subroutine say:

        PrintForm1.Print()

When the human runs the program and clicks the Print button, the computer will print most of Form1 onto paper.

The computer doesn’t bother printing Form1’s border or Text (title). It prints just Form1’s middle, including the objects in it.


Hard disk

If Form1’s subroutine says —

        My.Computer.FileSystem.WriteAllText("Joan.txt", 5 + 2, False)

the computer writes the number 7 (the answer to 5+2) onto your hard disk, in a file called Joan.txt. Unfortunately, that file is hard to access, since it’s buried in folders. (Specifically, it’s in the Debug folder, which is in the bin folder, which is in your program’s inner folder, which in your program’s outer folder, which is in the Projects folder, which is in the Visual Studio 2015 folder, which is in the Documents folder.)

If you don’t like the name Joan, invent a different name instead.

ProgramData folder This line is more practical:

        My.Computer.FileSystem.WriteAllText("\ProgramData\Joan.txt", 5 + 2, False)

It makes the computer write the number 7 (the answer to 5 + 2) onto your hard disk, in a file called Joan.txt, which is in the ProgramData folder.

After you’ve run the program (by clicking “Start”), you can see Joan.txt by doing this:

Click the File Explorer icon (which is at the screen’s bottom, on the taskbar, and looks like a yellow manila folder) then “This PC” (which is at the left). Double-click “C:” then “ProgramData” then “Joan”, whose hidden .txt ending makes the computer run the Notepad program, which shows you what’s in Joan.txt. You see that Joan.txt contains the answer, 7. When you finish admiring the answer, close the front 2 windows (by clicking their X buttons).

Documents folder If you want Joan.txt to be in the Documents folder instead of the ProgramData folder, type these lines instead:

        Dim doc

        doc = My.Computer.FileSystem.SpecialDirectories.MyDocuments

        My.Computer.FileSystem.WriteAllText(doc & "\Joan.txt", 5 + 2, False)

The top two lines makes the variable doc stand for the Documents folder. In the bottom line, the doc makes Joan.txt be in the Documents folder.

After you’ve run the program (by clicking “Start”), you can see Joan.txt by doing this:

Click the File Exploer icon (which is at the screen’s bottom, on the taskbar, and looks like a yellow manily folder) then “Documents”. Double-click “Joan”, whose hidden .txt ending makes the computer run the Notepad program, which shows you what’s in Joan.txt. You see that Joan.txt contains the answer, 7. When you finish admiring the answer, close the front 2 windows (by clicking their X buttons).

Append If Joan.txt exists before you run the subroutine, the subroutine erases that old Joan.txt to create a Joan.txt — unless you change the bottom line’s “False” to “True”, which makes the subroutine append the new answer to the end of the old Joan.txt, to make Joan.txt become longer and include both answers. In the bottom line, “True” means “append to the old file”; “False” means “don’t append to the old file; erase the old file.”

Reading Joan.txt After the computer has put an answer into Joan.txt, you can run a reading program that reads Joan.txt.

If Joan.txt is in the ProgramData folder, the reading program can have Form1’s subroutine say:

        Text = My.Computer.FileSystem.ReadAllText("\ProgramData\Joan.txt”)

That line makes the computer read Joan.txt and tell you what answer Joan.txt contains.

If Joan.txt is in the Documents folder, the reading program can have Form1’s subroutine say:

        Dim doc

        doc = My.Computer.FileSystem.SpecialDirectories.MyDocuments

        Text = My.Computer.FileSystem.ReadAllText(doc & "\Joan.txt")

Those lines make doc be the Documents folder and make Text be the answer that the computer reads from doc’s Joan.txt.

Rich-text box Try this experiment.…

Create a new program. On Form1, put a rich-text box (so the human can type a document into the box) and put a Save button (a button whose title is “Save”).

To make the Save button work properly (so pressing it copies the human’s typing from the box to the hard disk), make the button’s subroutine be this:

        Dim doc

        doc = My.Computer.FileSystem.SpecialDirectories.My Documents

        RichTextBox1.SaveFile(doc & "\Joan.doc")

The bottom line means: take what’s in the rich-text box and save it as a file; put the file into the Documents folder and call it Joan.doc.

When the human runs that program, the computer will let the human type a document (essay) into the rich-text box. Then computer will wait for the human to click the Save button (which makes the computer copy the document to the hard disk’s Documents folder, in a rich-text file called Joan.doc).

You can see Joan.doc by doing this:

Click the File Explorer icon (the yellow manila folder at the screen’s bottom) then “Documents”. Double-click “Joan”, whose hidden .doc ending makes the computer run the Microsoft Word (or WordPad) program, which shows you what’s in Joan.doc. You see that Joan.doc contains the essay. When you finish admiring the essay, close the front 2 windows (by clicking their X buttons).

“Save As” dialog box That subroutine forces the document to be in the Documents folder and be called “Joan.doc”. Here’s how to make the subroutine more flexible, (so the human can choose what folder to put the document in and what name to give the document.…

Double-click the SaveFileDialog tool (which is in the Dialogs category). That creates a SaveFileDialog1 icon below Form1.

In the SaveFileDialog1’s property list, click “DefaultExt” and type “doc”. That will secretly put “.doc” at the end of every filename.


Make the Save button’s subroutine be this:

        SaveFileDialog1.ShowDialog()

        RichTextBox1.SaveFile(SaveFileDialog1.FileName)

When the human clicks the Save button, the subroutine’s top line makes the computer show the “Save As” dialog box, which lets the human invent a file name and choose a folder to put it in. For example, if the human types “Joe” (and then presses the Enter key), the file will be called “Joe.doc” (because the SaveFileDialog1’s property list said the default extension is “doc”).

The subroutine’s bottom line means: look at the document that was typed in RichTextBox1, and save it as a file on the hard disk, using the file name (and folder) that the human specified in the “Save As” dialog box.

Say “document” Since RichTextBox1’s main purpose is to handle a document, programmers prefer to say just “document” instead of “RichTextBox1” and write the Save button’s program this way:

        SaveFileDialog1.ShowDialog()

        document.SaveFile(SaveFileDialog1.FileName)

To do that, you must change the box’s name from “RichTextBox1” to “document”. Here’s how:

In RichTextBox1’s property list (which is at the screen’s bottom-right corner), click “(Name)” then type the word “document”, so the line looks like this:

(Name)                                       document

Reading Joan.doc After the computer has saved (copied) a document into your hard disk’s Joan.doc, you can run a
reading program that reads Joan.doc.

The reading program should have a rich text box named “document”. It should also have an “Open” button whose subroutine says:

        OpenFileDialog1.ShowDialog()

        document.LoadFile(OpenFileDialog1.FileName)

But to make the computer understand what “OpenFileDialog1” means, you must double-click the OpenFileDialog tool before typing that subroutine.

 

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 say “I love you”, and clicking “Hate” makes the computer say “I hate being a computer”.

Here’s how to accomplish all that.…

Double-click the MenuStrip tool (which is in the “Menus & Toolbars” category).

Click “Type Here” (which is near Form1’s top). Then you see a blank box (plus two “Type Here” boxes). In the blank box, type your menu’s first word (“Love”).

Click the box that’s to the right of “Love”. Type your menu’s second word (“Hate”).

Congratulations! You created a menu!


Create menu subroutines Double-click “Love”, then write this subroutine telling the computer what to do if “Love” is clicked:

    Private Sub LoveToolStripMenuItem_Click…

        Text = "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 “Form1.vb [Design]” tab.

Double-click “Hate”, then write this subroutine about clicking “Hate”:

    Private Sub HateToolStripMenuItem_Click…

        Text = "I hate being a computer"

    End Sub

Run the program Go ahead: run the program (by clicking “Start”). You see the menu bar you created:

  Love    Hate

Clicking “Love” makes the computer say “I love you”; clicking “Hate” makes the computer say “I hate being a computer”.

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). Look at Form1’s design (by clicking the “Form1.vb [Design]” tab). Click the “Type Here” that’s to the right of “Hate”. In the blank box that appears, type your menu’s third word (“Color”).

Create a pull-down menu To create Color’s pull-down menu (saying “Yellow” and “Red”), click the “Type Here” that’s under “Color”. In the blank box that appears, type “Yellow”. In the box under “Yellow”, type “Red”.

Congratulations! You created a pull-down menu!

Create menu subroutines Double-click “Yellow”, then write this subroutine about Yellow:

    Private Sub YellowToolStripMenuItem_Click…

        BackColor = Color.Yellow

    End Sub

Click the “Form1.vb [Design]” tab, then double-click “Red”, then write this subroutine about Red:

    Private Sub RedToolStripMenuItem_Click…

        BackColor = Color.Red

    End Sub

Run the program Go ahead: run the program (by clicking “Start”). 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 “Blue”, so the menu becomes this:

Yellow

Red

Blue

Let’s program the computer so clicking “Blue” makes this submenu appear to the right of Blue:

Light Blue

Dark Blue

Let’s program so clicking one of those kinds of blue 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). Look at Form1’s design (by clicking the “Form1.vb [Design]” tab). Click “Color” then the “Type Here” that’s under “Red”. In the blank box that appears, type pull-down menu’s third word (“Blue”).

Create a submenu To create Blue’s submenu (saying “Light Blue” and “Dark Blue”), click the “Type Here” that’s to the right of “Blue”. In the blank box that appears, type “Light Blue”. In the box under “Light Blue”, type “Dark Blue”.

Congratulations! You created a submenu!

Creating a submenu for Blue made a right-arrow appear next to “Blue”, so Color’s pull-down menu looks like this:

Yellow

Red

Blue         8

That right-arrow means “has a submenu”.

Create subroutines Double-click “Light Blue”, then write this subroutine about Light Blue:

    Private Sub LightBlueToolStripMenuItem_Click…

        BackColor = Color.LightBlue

    End Sub

Click the “Form1.vb [Design]” tab, then double-click “Dark Blue”, then write this subroutine about Dark Blue:

    Private Sub DarkBlueToolStripMenuItem_Click…

        BackColor = Color.DarkBlue

    End Sub

Run the program Go ahead: run the program (by clicking “Start”). You see the menu bar you created:

  Love    Hate    Color

Clicking “Color” makes the computer show Color’s pull-down menu; clicking “Blue” makes the computer show Blue’s submenu; then clicking “Light Blue” or “Dark Blue” makes Form1’s background turn that color.

Rearranging menu items

After you’ve created a menu, you can rearrange its items. Here’s how.…

If your program is still running, stop it (by clicking its X button). Look at Form1’s design (by clicking the “Form1.vb [Design]” tab).

To delete an item, click it then press the Delete key. If you change your mind, click the Undo button (which shows a blue arrow bending toward the left).

 To move an item that’s on the menu bar (“Love”, “Hate”, or “Color”), drag that item across to where you want it — and, to make sure the computer doesn’t ignore you, drag slightly farther. To move an item that’s on a pull-down menu (“Yellow”, “Red”, or “Blue”) or submenu (“Light Blue” or “Dark Blue”), drag the item up or down to where you want it — and to make sure the computer doesn’t ignore you, drag slightly farther.

Minimalist word processor

Here’s how to invent a minimalist word-processing program.

Big Form1

Create a new program. Widen Form 1 (by dragging its bottom-right corner toward the right).

Tool strip

Onto Form 1, put a tool strip (toolbar) by doing this:

Double-click the ToolStrip tool (which is in the “Menus & Toolbars” category). That puts a ToolStrip1 icon below Form 1. Right-click that icon then click “Insert Standard Items”. That makes these 7 icons appear across Form 1’s top: New, Open, Save, Print, Cut, Copy, Paste, and Help. Each icon will act as a button.

Rich text box

Onto Form1, put a rich text box (by double-clicking the RichTextBox tool). Give that box the desired properties by doing this:

Click the box’s right-arrow (which is near the box’s top-right corner) then “Dock in parent container”. That makes the box expand to fill the rest of Form1: the only things above the box are the tool strip and the title bar (which says Form1).

In the box’s property list (which is at the screen’s bottom-right corner), scroll up until you see “EnableAutoDragDrop”, then click “EnableAutoDragDrop” and press the T key, so the line becomes this:

EnableAutoDragDrop                      True

Scroll up farther until you see “(Name)”, then click “(Name)” and type “document”, so the line becomes this:

(Name)                                             document

More tools

Double-click these tools, which you’ll need to finish the program:

OpenFileDialog (which is in the “Dialogs” category)

SaveFileDialog (which is in the “Dialogs” category)

PrintForm         (which is in the “Visual Basic PowerPacks” category)

Then icons for those tools appear below Form1.

Subroutines

For each button on the tool strip, write a subroutine. Here’s how.…

Double-click the tool strip’s first button (the New button, which looks like a blank sheet of paper with a folded corner). Type this line (for the New button’s subroutine):

        document.Clear()

Make Form1 appear again (by clicking the “Form1.vb [Design]” tab). Double-click the tool strip’s next button (the Open button, which looks like a yellow manila folder that’s opening). Type these lines (for the Open button’s subroutine):

        OpenFileDialog1.ShowDialog()

        document.LoadFile(OpenFileDialog1.FileName)

Make Form1 appear again (by clicking the “Form1vb [Design]” tab). In similar fashion, type these lines for the Save button:

        SaveFileDialog1.ShowDialog()

        document.SaveFile(SaveFileDialog1.FileName)

Type this line for the Print button:

        PrintForm1.Print()

Type this line for the Cut button:

        document.Cut()


 

Type this line for the Copy button:

        document.Copy()

Type this line for the Paste button:

        document.Paste()

Type this line for the Help button:

        MsgBox("This is word processor version 1")

Run

When you run the program (by clicking “Start”), the program works correctly, if you did what I said!

Congratulations on creating a word-processing program.

The program’s main limitations are:

It doesn’t let you change margins (except by dragging Form1’s bottom-right corner).

It doesn’t let you change fonts.

Its Print button prints just part of the document. (It prints just the part that’s visible on Form1 at the moment, and it can’t print any part that’s too far to the right to fit on the paper.)

Surpassing those limitations would require subroutines that are much longer!

 

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  x

            MsgBox("I worship your feet")

            MsgBox("But please wash them")

        Loop

The lines being repeated (the MsgBox lines) should be between the words Do and Loop and indented. (After you’ve typed the word “Do” and pressed Enter, the computer will automatically type the word “Loop” and created an indented blank space for you to type in.)

Run the program (by clicking “Start”). 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:

Click the Stop Debugging button (a blue square near the screen’s top center).

That works just if you’re in the Visual Basic environment (so you see the Stop Debugging button). If you’re not in the Visual Basic environment (because you’re running the .exe file directly), the only way to abort a looping program is to shut down the computer (click the Start button then, in Windows 7, click Shutdown) or try this:

While holding down the Ctrl and Alt keys, tap the Delete key. Click “Start Task Manager” then the “Applications” tab (which is at the screen’s top-left corner) then your program’s name then “End Task”. If you’re lucky, that aborts the program. Close the Windows Task Manager window (by clicking its X button).

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.

Disappearing-message-box bug

When running a loop, the computer might accidentally
lose the program’s focus and forget to show the message box. To make the message box reappear, click the message box’s button, which is on the taskbar. (The taskbar is at the screen’s bottom and runs from the Start button to the clock.) Try double-clicking the message box’s button. To run the program again, try clicking the green right-arrow (instead of pressing the F5 key).

GoTo

Instead of typing —

        Do 

            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

(When you type that subroutine, the computer automatically spaces it correctly: when you press Enter at the top line’s end, the computer automatically unindents “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 abort the program (by clicking the Stop Debugging button, twice).

You can give a line a short name (such as joe) or a long name (such as BeginningOfMyFavoriteLoop). The name can even be a number (such as 10). Put the name at the line’s beginning. After the name, put a colon (the symbol “:”).

The line’s name (such as joe or BeginningOfMyFavoriteLoop or 10) is called the line’s label.

Skip ahead This subroutine is insulting:

        MsgBox("Your face is outstanding.")

        MsgBox("It belongs in a horror movie.")

        MsgBox("It deserves an award!")


Let’s turn that insult into a compliment. To do that, insert the shaded items:

        MsgBox("Your face is outstanding.")

        GoTo conclusion

        MsgBox("It belongs in a horror movie.")

conclusion: MsgBox("It deserves an award!")

The computer begins by saying “Your face is outstanding.” Then the computer does GoTo conclusion, which makes the computer Go skip down To the conclusion line, which says “It deserves an award!” So the subroutine makes the computer say just —

Your face is outstanding.

and:

It deserves an award!

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 subroutine.

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 usually say Do…Loop instead of GoTo, I 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 make Form1’s subroutine say this:

        Dim guess

AskTheHuman: guess = InputBox("What's my favorite color?")

        If guess = "pink" Then

            MsgBox("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 says:

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:

        Dim guess

        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

        MsgBox("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 nicely (without abortion) 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 makes the computer say:

Congratulations! You discovered my favorite color.

Loop Until Here’s another way to program the guessing game:

        Dim guess

        Do

            MsgBox("You haven't guessed my favorite color yet!")

            guess = InputBox("What's my favorite color?")

        Loop Until guess = "pink"

        MsgBox("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 say these sentences:

I like the number 1

I like the number 2

I like the number 3

I like the number 4

I like the number 5

To do that, put these lines into Form1’s subroutine:

        For x = 1 To 5

            MsgBox("I like the number " & x)

        Next

The top line (For x = 1 To 5) says that x will be every number from 1 to 5; so x will be 1, then 2, then 3, then 4, then 5. The line underneath (which the computer indents) says what to do about each x: it says to create a message box saying “I like the number ” and x.

Whenever a subroutine says the word For, it must also say Next; so the bottom line says Next. The computer types the word “Next” for you automatically.

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 say “I like the number ” and an x. The first time, the x will be 1, so the computer will say:

I like the number 1

The next time, the x will be 2, so the computer will say:

I like the number 2

The computer will say similar sentences, for every number from 1 up to 5.


Monster song Let’s make the computer say these lyrics:

I saw 2 monsters

Tra-la-la!

I saw 3 monsters

Tra-la-la!

I saw 4 monsters

Tra-la-la!

They all had a party: ha-ha-ha!

To do that, type these lines —

The first line of each verse:       MsgBox("I saw " & x & " monsters")

The second line of each verse:  MsgBox("Tra-la-la!")

and make x be every number from 2 up to 4:

        For x = 2 To 4

            MsgBox("I saw " & x & " monsters")

            MsgBox("Tra-la-la!")

        Next

At the end of the song, say the closing line:

        For x = 2 To 4

            MsgBox("I saw " & x & " monsters")

            MsgBox("Tra-la-la!")

        Next

        MsgBox("They all had a party: ha-ha-ha!")

That program makes the computer print the entire song.

Here’s an analysis:

                       For x = 2 To 4

The computer will do indented lines       MsgBox("I saw " & x & " monsters")

repeatedly, for x=2, x=3, and x=4.          MsgBox("Tra-la-la!")

                       Next

Then the computer will do this once. MsgBox("They all had a party: 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

            MsgBox("I saw " & i & " monsters")

            MsgBox("Tra-la-la!")

        Next

        MsgBox("They all had a party: 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 a 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.

Say 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 say 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 —

        MsgBox("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

            MsgBox("The square of " & i & " is " & i * i)

        Next


Count how many copies This program makes the computer say “I love you” 4 times:

        For i = 1 To 4

            MsgBox("I love you")

        Next

Here’s a smarter program, which asks how many times you want the computer to say “I love you”:

        Dim n

        n = Val(InputBox("How many times do you want me to love you?"))

        For i = 1 To n

            MsgBox("I love you")

        Next

When you run that program, the computer asks:

How many times do you want me to love you?

If you answer 5 (and click the OK button), the n becomes 5 (so the computer says “I love you” 5 times). If you answer 7 instead, the computer says “I love you” 7 times. Get as much love as you like!

That program illustrates this rule:

To make the For...Next loop be flexible,

say “For i = 1 To n” and let the human input the n.

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

            MsgBox(i)

        Next

        MsgBox("Blast off!")

The computer will say:

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:

        Text = 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 say:

64

In the expression “4 ^ 3”, the 4 is called the base; the 3 is called the exponent or power.

Here’s another example:

        Text = 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 say the answer, 1000000.

Here’s another example:

        Text = 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 say 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 pre-algebra). For example, suppose you say:

        Text = 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:

        Text = Math.Sqrt(9)

The computer will print 3.

The symbol Math.Sqrt 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).

Math.Sqrt(9) gives the same answer as 9 ^ .5. The computer handles Math.Sqrt(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:

        Text = 64 ^ (1 / 3)

The computer will say 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 Math.Abs, Fix, Int, Math.Ceiling, Math.Round, or Math.Sign.

Math.Abs removes any minus sign. (“Abs” is short for “Absolute value”.) For example, the Math.Abs of -3.89 is 3.89. So if you say Text = Math.Abs(-3.89), the computer will say just 3.89.

Fix removes any digits after the decimal point. For example, the Fix of 3.89 is 3. So if you say Text = Fix(3.89), the computer will say 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).

Math.Ceiling rounds the number UP to an integer that’s HIGHER. For example, the Math.Ceiling of 3.89 is 4 (because 4 is an integer that’s higher than 3.89); the Math.Ceiling of -3.89 is -3 (because -3 is higher than -3.89).

Math.Round can round to the NEAREST integer. For example, the Math.Round of 3.89 is 4. The Math.Round of -3.89 is -4. The Math.Round of a number ending in .5 is an integer that’s even (not odd); for example, the Math.Round of 26.5 is 26 (because 26 is even), but the Math.Round of 27.5 is 28 (because 28 is even); this rounding method is called
unbiased rounding and explained in the next section (“Types of data”).
If you want traditional rounding instead of unbiased rounding, ask for Math.Round(26.5,System.MidpointRounding.AwayFromZero), which produces 27. If you say Text = Math.Round(865.739, 2), the computer will round 865.739 to 2 decimal places and say 865.74.

Math.Sign removes ALL the digits and replaces them with a 1, unless the number is 0. For example, the Math.Sign of 3.89 is 1. The Math.Sign of -3.89 is -1. The Math.Sign of 0 is just 0.

Math.Abs, Fix, Int, Math.Ceiling, Math.Round, and Math.Sign 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.

Pi

A circle’s circumference (the distance around a circle) is about 3 times as long as the circle’s diameter (the distance across the circle). So the circumference divided by the diameter is about 3. More precisely, it’s pi, which is about 3.1415926535897931, a number that Visual Basic calls Math.PI. If you type —

        Text = Math.PI

the computer will display this approximation:

3.14159265358979

Avoid “Math.”

Many of those functions expect you to type “Math.” To avoid having to type “Math.”, put this line at your program’s top (above “Public Class Form1”):

Imports System.Math

Then you can omit “Math.” For example, instead of typing —

        Text = Math.Sqrt(9)

you can type just:

        Text = Sqrt(9)

Instead of typing —

        Text = Math.PI

you can type just:

        Text = PI


Types of data

If you want x to be a variable in your subroutine, you must warn the computer by giving your subroutine a command such as:

        Dim x

Here’s how to make your program run faster, consume less RAM, and correct more errors: instead of saying just “Dim x”, warn the computer what type of data the x will stand for, by giving one of these 8 popular commands:

Command                        Meaning                                                                                                                                                     RAM          Speed

Dim x As Integer x will be a number from 0 to 2147483647,                  with no decimal point, but maybe a negative sign           4 bytes      fastest

Dim x As Long    x will be a number from 0 to 9223372036854775807, with no decimal point, but maybe a negative sign           8 bytes       fast

Dim x As Double   x will be a number from 0 to 1E308,  with maybe a decimal point and negative sign,          15-digit accuracy    8 bytes       fast

Dim x As Decimal  x will be a number having up to 28 digits, with maybe a decimal point and negative sign,   28-digit accuracy  16 bytes      slowest

Dim x As Date    x will be a date and time (such as #12/31/2009 11:59:30 PM#), with a year between 1 and 9999                       8 bytes       slow

Dim x As Boolean x will be either the word True or the word False                                                                                                2 bytes       fast

Dim x As String    x will be a string (such as “I love you”) up to 2 billion characters long                   2 bytes per character, plus  10 bytes       slow

Dim x As Char     x will be a single character (such as “j”)                                                                                                            2 bytes       fast

Here’s how to choose among them:

If x stands for a reasonably small number (2147483647 or less) without a decimal point, choose Integer.

If x stands for a longer number (up to 922337203854775807) without a decimal point, choose Long.

If x stands for a number that’s even bigger or has a decimal point, choose Double unless you need more than 15-digit accuracy, which demands Decimal.

If x stands for a date or time, choose Date.

If x stands for the word True or the word False, choose Boolean.

If x stands for a single character (such as “c”), choose Char. If x stands for a longer string, choose String.

For example, if you want x to be 3000000, say:

        Dim x As Integer

        x = 3000000

According to the chart’s top line, saying “Dim x As Integer” makes x consume 4 bytes of RAM. The computer can store 3000000 (or any integer up to 2147483647) in just 4 bytes of RAM, because the computer stores the number by using a special trick called
binary representation.

These 7 variations are less popular:

Instead of Integer, you can choose UInteger (which means unsigned integer).

It can handle numbers that are twice as big (up to 4294967295) but can’t handle a negative sign.

Instead of Long, you can choose ULong (which means unsigned long).

It can handle numbers that are twice as big (up to 18446744073709551615) but can’t handle a negative sign.

Instead of Integer (which consumes 4 bytes), you can choose Short (which consumes just 2 bytes and is limited to numbers up to 32767) or SByte (which consumes just 1 byte and is limited to numbers up to 127). But those alternatives run slow, because the Pentium chip was designed to handle 4-byte integers, not shorter integers. Use those alternatives just if you’re worried about the number of bytes. Here are other alternatives, which also run slow: UShort (which consumes 2 bytes, handles numbers up to 65535, no decimals or negatives) and Byte (which consumes 1 byte, handles numbers up to 255, no decimals or negatives).

Instead of Double, you can choose Single (which means single-length numbers). It consumes fewer bytes (4 instead of 8) but runs slow (because the Pentium chip was designed to handle decimal points in 8-byte numbers, not shorter ones). It has less accuracy (7-digit instead of 15-digit) and is restricted to smaller numbers (up to 3E38, not 1E308). Use it just if you’re worried about the number of bytes.


Details

Here are more details about the 8 popular Dim commands.

Integer An Integer 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 Integer:

0   1   2   3   10   52   53   1000   2147483647

   -1  -2  -3  -10  -52  -53   1000  -2147483647

Technical note: although 2147483648 is slightly too big to be an Integer, -2147483648 is a special number that can be an Integer, though it’s rarely used and must be written as:

-2147483647 - 1

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.

To round, Visual Basic 2015 makes the computer use this strange method, called unbiased rounding:

If the number’s decimal part is less than .5 (for example, if it’s .4), the computer rounds down. For example, 26.4 rounds down to 26.

If the number’s decimal part is more than .5 (for example, if it’s .51 or .6), the computer rounds up. For example, 26.51 rounds up to 27.

If the number’s decimal part is exactly .5 (not less, not more, not .51), the computer uses this strange method: it round to the nearest integer that’s even (not odd). For example, 26.5 rounds down to 26 (since 26 is even), but 27.5 rounds up to 28 (since 28 is even).

That makes .5 sometimes round down and sometimes rounds up, so there’s no bias toward rounding in a particular direction. That unbiased rounding method appeals to statisticians (and a few economists and very few bankers) who want to eliminate bias from rounded results. It’s called unbiased rounding (or
round-to-even or statisticians rounding or bankers rounding or Dutch rounding or Gaussian rounding).

Long A Long is a number from 0 to 9223372036854775807, 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  9223372036854775807

0 -1 -2 -3 -10 -52 -53 -1000 -9223372036854775807

Technical note: although 9223372036854775808 is slightly too big to be a Long, -9223372036854775808 is a special number that can be a Long, though it’s rarely used and must be written as:

-9223372036854775807 - 1

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. (To round, the computer uses unbiased rounding.)

If you write a number that has no decimal point and is small (no more than 2147483647), the computer assumes you want it to be an Integer. If you want it to be a Long instead,
put L after it, like this: 57L. For example, if you tell the computer to multiply 3000 by 1000000, like this —

        Text = 3000 * 1000000

the computer assumes you want to multiply the Integer 3000 by the Integer 1000000; but the answer is too long to be an Integer, so the computer gripes (by saying “not representable in type ‘Integer’”). Multiplying 3000 by 1000000 is okay if you say the numbers are Longs, not Integers, like this:

        Text = 3000L & 1000000L

Then the computer will show the correct answer:

3000000000


Double A Double is a number from 0 to 1E308 (which is a “1 followed by 308 zeros”), 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 Double:

0  1  2  3  4.99  4.9995  4.999527  1000.236  26127.85  1E308

0 -1 -2 -3 -4.99 -4.9995 -4.999527 -1000.236 -26127.85 -1E308

The computer manages to store a Double rather briefly (just 8 bytes) by “cheating”: 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

        Text = 100 / 3

the computer will show 15 digits:

33.3333333333333

If you say —

        Dim x As Double

        x = 1000000.000000269

        Text = x

the computer will round to 15 digits and show:

1000000.00000027

When handling Double 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, y As Double

        x = 8000.1

        y = x - 8000

        Text = 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! That’s the drawback of Double: you can’t trust the last few digits of the answer! Double is accurate enough for most scientists, engineers, and statisticians, since they realize all measurements of the real world are just approximations; but Double is not good enough for accountants who fret over every penny. Double’s errors drive accountants bananas. For accounting problems that involve decimals, consider using Decimal instead of Double, since Decimal is always accurate, though slower.

Technical notes:

A Double can be slightly bigger than 1E308. The biggest permissible Double is actually 1.7976931348623157E308.

If a Double is at least a quadrillion (which is 1000000000000000) or tiny (less than .0001), the computer will display it by using E notation.

When you type a Double in your subroutine, the computer stores the first 16 significant digits accurately, stores an approximation of the 17th significant digit, and ignores the rest.

If you type a number that has no decimal point and no E, the computer will think you’re trying to type an Integer or a Long; and if it has many digits, the computer will complain that a Long is not allowed to have so many digits. To correct the problem, indicate you’re trying to type a Double, by putting .0 at the end of the number or using E notation.

When the computer displays an answer, it displays the first 15 significant digits and hides the rest, since it knows the rest are unreliable. For example, if you set Text equal to the biggest number (1.7976931348623157E308), the computer will display it rounded to 15 digits, so it will display 1.79769313486232E308.

The tiniest decimal the computer can handle accurately is 1E-308 (which is a decimal point followed by 308 digits, 307 of which are zeros). If you try to go tinier, the computer will give you a rough approximation. The tiniest permissible Double is 4.9406564584126544E-324; if you try to go tinier than that, the computer will say 0.

Decimal If you say “Dim x as Decimal” (instead of “Dim x as Double”, the computer will store x very accurately (28 digits, and sometimes a 29th). The computer handles Decimals slower than any other kind of number, so say “Dim x as Decimal” just if you need extra accuracy and don’t care about speed.

If you say “Dim x as Decimal”, the computer actually stores all x’s digits as an extra-long integer and also stores a note about where the decimal point belongs.

To write a Decimal number, put D after the number, to emphasize that the number is a Decimal, not a Double, like this:

        Dim x As Decimal

        x = 1000000.000000269D

The biggest permissible Decimal is 79228162514264337593543950335D (which has 29 digits and no decimal point). The tiniest permissible Decimal is 0.0000000000000000000000000001D (which has 27 zeros after the decimal point).

A Decimal number cannot contain E. It’s limited to 28 (or 29) digits. When counting how many digits are in the number, you must count the zeros: the limit is indeed 28 (or 29) digits (not 28 “significant digits”).

Date A Date is a date with time. For example, these lines make x be December 31, 2009, at 30 seconds after 11:59 PM:

        Dim x As Date

        x = #12/31/2009 11:59:30 PM#

        Text = x

Notice you must put the symbol # before and after the date-with-time. The computer will print:

12/31/2009 11:59:30 PM

For the year, you can pick 2009 or 1999 or 1776 or 1492 or even earlier. You can pick any year from 1 (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 midnight, 12:00:00 AM).

If you leave out the date, the computer assumes you mean the beginning of modern times (which is January 1 in the year 1).

To avoid pissing off people who don’t like those assumptions, the computer avoids displaying 12:00:00 AM and avoids displaying 1/1/1. For example, if you leave out the time of day and type this —

        Dim x As Date

        x = #12/31/2009#

        Text = x

x will be #12/31/2009 12:00:00 AM# but the computer will display just:

12/31/2009

If you leave out the date and type this —

        Dim x As Date

        x = #11:59:30 PM#

        Text = x

x will be #1/1/1 11:59:30 PM# but the computer will display just:

11:59:30 PM

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, 2009 (at 30.16 seconds after 11:59 PM), x will become #12/31/2009 11:59:30 PM#.

Boolean A Boolean is either the word True or the word False. Here’s an example:

        Dim x As Boolean

        x = True

        Text = x

The computer will display:

True

Here’s another example:

        Dim x As Boolean

        x = False

        Text = x

The computer will display:

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 try to say “x = 1” (or say that x is any other non-zero number), the computer will make x be True.

It’s called “Boolean” to honor George Boole (the 19th-century mathematician who discovered that the word False acts like the number 0, and True acts like the number 1).

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"

        Text = x

The computer will display:

joy

Versions of Visual Basic before 2005 used a code called the American Standard Code for Information Interchange (Ascii), which consumed just 1 byte per character; but Visual Basic 2005, 2008, 2010, 2012, 2013, and 2015 use a different code instead, called Unicode, which uses 2 bytes per character, to permit fancier characters for foreign languages.

Since the string “joy” contains 3 characters, and each character consumes 2 bytes, x consumes 6 bytes of RAM — plus 10 bytes to remember how long the string is. So altogether, x consumes 16 bytes of RAM.

If you say “Dim x As String” and try to say “x = 9 + 3.5”, the computer will look at the equation’s right side, realize it’s 12.5, and try to make x be 12.5; but because of the “Dim x as String”, the computer must turn x into a string, so x will become the string “12.5” (which is four characters long).

Character A Char is a single character, such as “j”. It consumes just 2 bytes. To emphasize that “j” is just a single character, not “a string whose length is 1”, write c after the “j”, like this:

        Dim x As Char

        x = "j"c

        Text = x

The computer will display:

j

So if x is a Char, the computer requires just 2 bytes to store it. (To store a String, the computer needs 2 bytes per character, plus 10 bytes to store the string’s length; but to store a Char, the computer needs just 2 bytes, since the computer doesn’t have to store a length.)

If you say —

        Dim x As Char

        x = "hat"

the x will be just the first character of the string “hat”, so x will be just “h”. Then if you say —

        Text = x

the computer will display just:

h

Object You’ve learned that x can stand for a number, date, Boolean, string, or character.

Here’s another possibility: x can stand for an object, such as Form1 or Button1 or any other VB thing, such as Color.Red.

For example, suppose you created a button called Button1. If you put this line in Form1’s subroutine, Button1’s title will become “Click me”:

        Button1.Title = "Click me"

These lines do the same thing:

        Dim x As Object

        x = Button1

        x.Text = "Click me"

Saying “Dim x As Object” is vague. It has exactly the same meaning as “Dim x”, which is vague. If you say “Dim x As Object” (or just “Dim x”), you’re saying that x stands for a Windows object (such as Form1 or Button1) or some other kind of object (such as a number, date, Boolean, string, or character). The computer handles such an x slowly: it consumes 4 bytes to remember what part of the RAM holds x’s details, plus several bytes to store the details.

Multiple variables

If you want x and y to be Integers, z to be a String, and temperature to be a Double, say this —

        Dim x, y As Integer

        Dim z As String

        Dim temperature as Double

or say it all in one line:

        Dim x, y As Integer, z As String, temperature As Double

Suffix

Here’s the normal way to make x be a String:

        Dim x As String

This way is shorter:

        Dim x$

That dollar sign means “As String”. The dollar sign is called a suffix (or type-declaration character).

You can use these suffixes:

Suffix     Meaning

$              As String

%              As Integer

&              As Long

#              As Double

@             As Decimal

!              As Single


Repeating the suffix Below the Dim line, you can type the suffix again if you wish. For example, after you’ve made x be a string by saying —

        Dim x$

you can say either —

        x = "I love you"

or this, which means the same thing:

        x$ = "I love you"

The computer doesn’t care whether you type the $ again. Type it just if you want to emphasize it to other programmers who look at your subroutine.

Constants

Your subroutine can mention variables (such as x and y) and constants (such as 3.7 and “I love you”). Here’s how the computer tells a constant’s type:

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 enclosed in quotation marks (such as “I love you”), it’s a String, unless it has a c afterwards (such as “j”c), which makes it a Char (and is limited to just one character).

If the constant is a number, here’s what happens.…

If the number has no decimal point and no E and is short (between -2147483648 and 2147483647), it’s an Integer. If the number has no decimal point and no E and is between -9223372036854775808 and 9223372036854775807 but is not an Integer, it’s a Long. Any other number is a Double.

To force a number to be a Decimal instead, put D (or @) after the number, like this: 4.95D

To force a number to be a Long (even though it’s small enough to be an Integer), put L (or &) after the number, like this: 52L

To force a number to be a Double (even though it’s simple enough to be an Integer or Long), put .0 after the number, like this: 52.0.

VarType

Each type of constant has a code number:

Type of constant    Code number

Integer                          3

Long                           20

Double                          5

Decimal                       14

Date                              7

Boolean                       11

String                            8

Char                            18

Object                           9

If you say VarType, the computer will examine a constant and tell you its code number. For example, if you say —

        Text = VarType(4.95D)

the computer will examine 4.95D, realize it’s a Decimal, and say Decimal’s code number, which is:

14

Here are more examples:

If you say Text =  VarType (“I love you”), the computer will examine “I love you”, realize it’s a String, and print String’s code number, which is 8.

If you say Text = VarType(2000000000), the computer will examine 2000000000, realize it’s an Integer, and print Integer’s code number, which is 3.

If you say Text = VarType(300000000), the computer will examine 300000000, realize it’s a Long, and print Long’s code number, which is 20.


VarType of a variable If you say 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 Decimal

        Text = VarType(x)

the computer will say Decimal’s code number, which is 14.

If you say just “Dim x” (or “Dim x As Object”) without specifying further details of x’s type, VarType(x) will be whatever type the x acquires. For example, if you say —

        Dim x

        x = 4.95D

        Type = VarType(x)

the computer will print Decimal’s code number, which is 14.

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 —

        Text = TypeName(4.95D)

the computer will say:

Decimal

Instead of saying “Object” (or “Nothing”), the computer will try to be more specific. For example, if you created a command button called Button1 and say —

        Text = TypeName(Button1)

the computer will say:

Button

If x is an Object but doesn’t have a more specific value or type yet, “Text = TypeName(x)” will make the computer say:

Nothing

Initial value

Instead of saying —

       Dim x As Integer

       x = 7

you can combine those two lines into this single line:

       Dim x As Integer = 7

In that line, 7 is called x’s initial value (or initializer), because it’s what x is initially (in the beginning).

You can shorten that line further, by saying just this:

       Dim x = 7

Since 7 is an Integer (according to the rules about which constants are Integers), the computer will assume you also mean “x As Integer”. If you say this instead —

        Dim x = 7.0

the computer will assume you mean “x As Double”.

Saying “Dim x = 5” has a slightly different effect than saying “Dim x” then “x = 5”.Compare these subroutines:

Dim x

x = 5            Dim x = 5

x = 8.4          x = 8.4

Text = x         Text = x

In the left subroutine, the Dim line says x is a vague variable (an object). The next line says x is 5. The next line changes x to 8.4, so Text will be 8.4. In the right-hand subroutine, the first line says x is 5 but also makes x be an integer variable (since that line implies “x As Integer”); since x is an integer variable, the next line makes x be 8 (not 8.4), so Text will be just 8.

Operations

When you do operations (add, subtract, multiply, divide, exponents, or beyond), 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 Decimal, the answer is Decimal.

If one of the numbers is Single and the other is Single or Decimal, the answer is Single.

In all other situations, the answer is 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 makes the answer be the same type. (Exception: if both “numbers” are actually Boolean, the computer makes the answer be Short.)

If the numbers have different types from each other, and both types are signed (permit minus signs), the computer notices which type is wider (can handle more numbers) and makes the answer be that type. Here are the signed types, from narrowest to widest: SByte, Short, Integer, Long, Decimal, Single, Double. (Single is wider than Decimal because Single can handle higher powers of 10.) For example, if one number is an Integer and the other number is a Long, the answer is a Long (because Long is wider than Integer).

If the numbers have different types from each other, and at least one of those types is unsigned (Boolean, Byte, UShort, UInteger, or ULong), the computer makes the answer be the wider type — or a signed type that’s even wider.

Advanced math Here’s how the computer handles advanced math:

Math.PI and Math.Sqrt(x) are Double.

Math.Sign(x) is an Integer.

Math.Abs(x) and Fix(x) and Int(x) are the same type as x, if x’s type is signed. If x’s type is unsigned, the computer turns x into a wider signed number first.

Math.Ceiling(x) and Math.Round(x) are Double, if x is a Double or Single. They’re Decimal if x is otherwise.

Combine When you combine strings or numbers (by using the symbol “&”), the answer is a string.

Form1 declarations

Normally, each subroutine has its own variables. For example, if Form1’s subroutine uses a variable called x, and Button1’s subroutine uses a variable that’s also called x, Form1’s x has nothing to do with Button1’s x. Form1’s x is stored in a different part of RAM from Button1’s x. If Form1 says x = 5, Button1’s x remains unaffected by that statement.

If you want Form1’s x to be the same as Button1’s x and use the same RAM, say “Dim x” above the “Private Sub Form1” line instead of below.

Example For example, try this experiment.…

Create a new program. Double-click Form1, so you can type Form1’s subroutine. Your screen looks like this:

Public Class Form1

    Private Sub Form1_Load…

 

    End Sub

End Class

Click above the “Private Sub Form1” line and type “Dim x” there, so your screen looks like this:

Public Class Form1

    Dim x

    Private Sub Form1_Load…

 

    End Sub

End Class

Type Form1’s subroutine under the “Private Sub Form1” line, like this:

Public Class Form1

    Dim x

    Private Sub Form1_Load…

        x = 5

    End Sub

End Class

Create Button1 (by clicking the “Form1.vb [Design]” tab then double-clicking the Button tool). Double-click Button1, then type “Text = x” for Button1’s subroutine. Altogether, your screen looks like this:

Public Class Form1

    Dim x

    Private Sub Form1_Load…

        x = 5

    End Sub

 

    Private Sub Button1_Click…

        Text = x

    End Sub

End Class

Since the “Dim x” is above both subroutines (instead of being buried inside one subroutine), the x’s value affects both subroutines (not just one of them).

When you run that program (by clicking “Start”), Form1’s subroutine makes x be 5. Then when you click Button1, Button1’s subroutine makes Text be x, which is 5, so the computer says:

5

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

CDbl           convert to Double

CDec           convert to Decimal

CDate        convert to Date

CBool        convert to Boolean

CStr           convert to String

CChar        convert to Char

CUInt        convert to UInteger

CULng        convert to ULong

CShort      convert to Short

CSByte      convert to SByte

CUShort   convert to UShort

CByte       convert to Byte

CSng           convert to Single

CObj           convert to Object

For example, CInt(3.9) is “3.9 converted to the nearest Integer”, which is 4. If you say —

        Text = CInt(3.9)

the computer will say:

4

If you say —

        Text = CInt(3.9) + 2

the computer will say:

6

Arrays

Instead of being just a number, x can be a list of numbers.

Example For example, if you want x to be this list of numbers —

{81, 52, 207, 19}

type this in Form1’s subroutine:

        Dim x() = {81, 52, 207, 19}

In that line, the symbol “x()” means “x’s list”. Notice that when you type the list of numbers, you must put commas between the numbers and put the entire list of numbers in braces, {}. On your keyboard, the “{” symbol is to the right of the P key and requires you to hold down the Shift key.

Since all numbers in that list are Integers, you can improve that line by saying “As Integer”, like this:

        Dim x() As Integer = {81, 52, 207, 19}

If you don’t say “As Integer”, the computer will treat those numbers as just vague objects, and the program will run slower.

In x’s list, the starting number (81) is called x0 (pronounced “x subscripted by zero” or “x sub 0” or just “x 0”). The next number (52) is called x1 (pronounced “x subscripted by one” or “x sub 1” or just “x 1”). The next number is called x2. Then comes x3. So the four numbers in the list are called x0, x1, x2, and x3.

To make the computer say what x2 is, type this line:

        Text = x(2)

That line makes Text be x2, which is 207, so the computer will say:

207

Altogether, the subroutine says:

        Dim x() As Integer = {81, 52, 207, 19}

        Text = x(2)

The first line says x’s list is these Integers: 81, 52, 207, and 19. The bottom line makes the computer say x2’s number, which is 207.

This subroutine makes the computer say x2’s number (which is 207) in a message box:

        Dim x() As Integer = {81, 52, 207, 19}

        MsgBox(x(2))

This subroutine makes the computer say all 4 numbers:

        Dim x() As Integer = {81, 52, 207, 19}

        For i = 1 To 4

            MsgBox(x(i))

        Next

That makes the computer say the numbers for x(1), x(2), x(3), and x(4), so the computer will say 81, 52, 207, and 19.

Here’s a shorter way to make the computer say all 4 numbers:

        Dim x() As Integer = {81, 52, 207, 19}

        For Each i In x

            MsgBox(i)

        Next

That makes x’s list be {81, 52, 207, 19}, makes i be Each number In x (so i is 81, then 52, then 207, then 19), and makes the computer say each i.

Longer lists Instead of having just 4 numbers in the list, you can have 5 numbers, or 6 numbers, or a thousand numbers, or many billions of numbers. The list can be quite long! Your only limit is how much RAM your computer has.

Jargon Notice this jargon:

In a symbol such as x2, the lowered number (the 2) is called the subscript.

To create a subscript in your subroutine, use parentheses. For example, to create x2, type x(2).

A variable having subscripts is called an array. For example, x is an array if there’s an x0, x1, x2, etc.

Different types Instead of having Integers, you can have different types. For example, you can say:

        Dim x() As Double = {81.2, 51.7, 207.9, 19.5}

You can even say:

        Dim x() As String = {"love", "hate", "peace", "war"}

You can even have mixed types:

        Dim x() = {5, 91.3, "turkey", #11:59:30 PM#}

Uninitialized Instead of making the Dim line include a list of numbers, you can type the numbers underneath, if you warn the computer how many numbers will be in the list, like this:

        Dim x(2) As Double

        x(0) = 200.1

        x(1) = 700.4

        x(2) = 53.2

        Text = x(0) + x(1) + x(2)

The top line says x0, x1, and x2 will be Doubles. The next lines say x0 is 200.1, x1 is 700.4, and x2 is 53.2. The bottom line makes the computer say their sum:

953.7

In that top line, if you omit the “As Double”, the program will give the same answer but slower. But in that top line, the 2 is required, to warn the computer how many subscripts to reserve RAM for; if you omit the 2 (or type a lower number instead), the computer will gripe.

 

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. For example, if Form1’s subroutine says —

        MsgBox(Rnd)

        MsgBox(Rnd)

        MsgBox(Rnd)

the computer says these decimals:

.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.

These lines make the computer say 16 decimals:

        For i = 1 To 16

            MsgBox(Rnd)

        Next

You can say either Rnd or Rnd(); the computer doesn’t care. If you say just Rnd, the computer might change it to Rnd().

Percentages

When the computer says random 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 a program about Rnd again, you’ll see exactly the same decimals again, in the same order.

If you’d rather see a different list of decimals, say Randomize() at the subroutine’s top:

        Randomize()

        For i = 1 To 16

            MsgBox(Rnd)

        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 MsgBox("heads") Else MsgBox( "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”.

When you’ve typed that subroutine, the computer changes Rnd to Rnd(), so it looks like this:

Randomize()

If Rnd() < 0.5 Then MsgBox("heads") Else MsgBox( "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!

To write that subroutine shorter, say IIf:

Randomize()

MsgBox(IIf(Rnd() < 0.5, "heads", "tails"))

The bottom line creates a message box saying this: if the random number is less than .5, then “heads”, else “tails”.

This subroutine flips the coin 10 times:

Randomize()

For i = 1 To 10

    MsgBox(IIf(Rnd() < 0.5, "heads", "tails"))

Next

Love or hate?

Who loves ya, baby? These lines try to answer that question:

Randomize()

Dim x As String

x = InputBox("Type the name of someone you love")

If Rnd < 0.67 Then

    MsgBox(x & " loves you, too")

Else

    MsgBox(x & " hates your guts")

End If

The Randomize() line makes the value of Rnd depend on the clock. The Dim line says x will be a variable that stands for a String. 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 the computer will say “Suzy loves you, too”, but there’s a 33% chance the computer will instead say “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!

Here’s a shorter way to write that subroutine:

Randomize()

Dim x = InputBox("Type the name of someone you love")

MsgBox(x & IIf(Rnd < .67, " loves you, too", " hates your guts"))

The Randomize() line makes the value of Rnd depend on the clock. The Dim line makes the variable x be the response to “Type the name of someone you love”. The MsgBox line creates a message box that says x then this: if the random number is less than .67 then “ loves you, too” else “ hates your guts”.


Random integers

If you want a random integer from 1 to 10, ask for 1 + Int(Rnd * 10). 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.")

        Dim ComputerNumber = 1 + Int(Rnd * 10)

AskHuman: Dim 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

        MsgBox("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 makes the computer say:

Congratulations! You found my number!

Dice These lines make the computer roll a pair of dice:

        Randomize()

        MsgBox("I'm rolling a pair of dice")

        Dim a = 1 + Int(Rnd * 6)

        MsgBox("One of the dice says " & a)

        Dim b = 1 + Int(Rnd * 6)

        MsgBox("The other says " & b)

        MsgBox("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, Dim 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 says the total.

For example, a run might say these sentences:

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() = {"wonderful", "fairly good", "so-so", "fairly bad", "terrible"}

MsgBox("You will have a " & x(Int(Rnd * 5)) & " day today!")

The Dim line makes x be a list of 5 fortunes, so x0 is “wonderful”, x1 is “fairly good”, x2 is “so-so”, x3 is “fairly bad”, and x4 is “terrible”. Since Int(Rnd * 5) is a random integer from 0 to 4, the x(Int(Rnd * 5)) is a randomly chosen fortune. The computer will say —

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!