The Secret Guide to Computers

 home » read » visual basic 1  home  read  buy the book now!  contact us 


 
 

Fun

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.

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

Learn QBASIC, which is much easier than VB. I explained QBASIC on pages 376-467. 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 94-111 and 166-230. Read and practice whichever of those Windows programs you have access to.

Get a 17-inch monitor (or larger), and set its resolution to 1024-by-768 (or larger), so you can see all of VB’s controls well.

The current version of VB is VB 6. (Microsoft is trying to develop a VB 7, which is also called VB.Net.)

This chapter explains VB 6. (Other versions of Visual BASIC are similar.)

You can get VB 6 in several ways:

The cheapest is to get the Learning Edition, which includes a tutorial and lists for $109. The next step up is the Professional Edition, which includes more commands but no tutorial; it lists for $549. The Enterprise Edition includes even more commands and lists for $1299.

Another way to get VB is buy Visual Studio, which includes VB and several other programming languages. Version 6 of Visual Studio includes Visual Basic, Visual C++, Visual J++ (which is a version of Java), Visual FoxPro (which is a variant of DBASE), and other programming tools. The total list price for Visual Studio version 6 is $549 for the Professional Edition, $1619 for the Enterprise Edition.


VB resembles QBASIC. For example, VB uses these commands (which resemble QBASIC’s):

VB command                                       Page

Case "fine"                  479

Circle (1000, 2000), 500      493

Close                      508

Cls                          493

DefInt A-Z                   504

Dim x As Byte                 500

Dim x(3)                     505

Do                         495

Do Until EOF(1)              509

Else                       478

ElseIf age < 100 Then         478

End                          480

End If                       478

End Select                   479

End Sub                      469

EndDoc                       473

Exit Do                      496

Exit Sub                     480

For x = 1 To 12              496

GoTo joe                     495

If age < 18 Then Print "minor"477

Input #1, x                  508

Line (0, 0) - (1000, 2000)     493

Loop                       495

Loop Until guess = "pink"     496

MsgBox "Your hair looks messy"476

Next                       496

Open "joe.txt" For Output As 1508

Print 4 + 2                  469

Print #1, "eat"              508

PrintForm                    473

Private Sub Form_Load()        469

PSet (1000, 2000)             493

Randomize                    506

Select Case feeling           479

Set x = Command1              502

x = 47                       474

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

VB function                             Value       Page

Abs(-3.89)             3.89             499

CInt(3.9)              4                  504

Date                 varies           502

Date$                varies           502

EOF(1)                 varies           509

Fix(3.89)              3                  499

FormatNumber(27931.6)   “27,931.60”    494

FormatPercent(.75)      “75.00%”    494

InputBox("What name?")  varies           476

Int(3.89)              3                  499

LOF(1)                 varies           509

MsgBox("Fun?", vbYesNo)   varies           479

Now                    varies           502

RGB(255, 127, 0)        32767             481

Rnd                    varies           506

Round(3.89)            4                  499

Sgn(3.89)              1                  499

Sqr(9)                 3                  499

Tab(6)                 varies           493

Time                 varies           502

Time$                varies           502

Timer                varies           502

TypeName(4.95@)        “Currency”  504

Val(InputBox("Number?"))varies           476

VarType(4.95@)         6                 503


In VB, you never write “a long program”. Instead, you begin by drawing objects on the screen (as if you were using a graphics program). Then for each object, you write a little program (called a subroutine) that tells the computer how to manipulate the object. VB handles these objects:

VB object             Page

CheckBox      485

ComboBox      487

CommandButton   483

Form1        469

Form2        489

Frame        488

HScrollBar    488

Label        485

Line         487

ListBox       486

Menu         490

OptionButton  484

Printer       473

Shape        487

TextBox       486

Timer        489

VScrollBar    488

Each object has properties, which you can manipulate:

VB property           Popular use     Page

AutoRedraw      Form1      469

AutoSize        Label      485

BackColor       Form1      481

BorderColor     Line       487

Caption         Form1      480

Enabled         Timer      489

FillColor       Shape      487

FillStyle       Shape      487

Font          Form1      481

ForeColor       Form1      481

Height          Form1      482

Interval        Timer      489

LargeChange     HScrollBar   488

Left          Form1      482

List          ListBox      486

Max             HScrollBar   488

MaxButton       Form1      482

Min             HScrollBar   488

MultiLine       TextBox      487

MultiSelect     ListBox      486

PasswordChar    TextBox      487

ScrollBars      TextBox      487

Selected        ListBox      486

Shape         Shape      487

SmallChange     HScrollBar   488

StartUpPositionForm1      482

Style         ComboBox     487

Text          ListBox      486

Top             Form1      482

Value         OptionButton484

Visible         Form2      489

Width         Form1      482

WindowState     Form1      482

WordWrap        Label      485


Copy VB to the hard disk

Here’s how to copy Visual Studio (version 6, Enterprise Edition) to the hard disk. (Other versions of Visual Studio and VB are similar.)

Make sure your computer contains Windows 98 (or Windows Me) and Internet Explorer 5 (or 5.5).

Turn on the computer without any floppy or CD-ROM disks in the drives, so the computer runs Windows 98 and the computer’s bottom left corner says Start. Put Visual Studio 6.0’s Disc 1 into the CD-ROM drive. The computer will say “Visual Studio 6.0”. Press ENTER. Click “I accept the agreement”. Press ENTER.

Type the 10-digit CD key number (printed on the orange sticker at the back of the CD-ROM disk’s square case). Press TAB. Type your name. Press TAB. Type the name of your company (if any). Press ENTER four times.

You’ll see a product ID. Copy it onto the registration form that you’ll mail to Microsoft. Press ENTER three times.

Finally, the computer will copy Visual Studio to the hard disk. Click “OK”. Press ENTER. The computer will reboot itself.

The computer will say “Install MSDN”. Put the MSDN Library’s Disc 1 into the CD-ROM drive. Click “Next”. Press ENTER.

You’ll see an MSDN product ID. Copy it onto a sheet of paper. Press ENTER three times The computer will copy the MSDN Library to the hard disk. Press ENTER six times.

Remove the check mark from the “Register Now” box (by clicking it). Press ENTER.

Start VB

To start using VB, click “Start” then “Programs”. (Then click “Microsoft Visual Studio 6.0”, if you see that choice.)

Click “Microsoft Visual Basic 6.0”.

Create simple programs

Press ENTER. (That has the same effect as double-clicking “Standard EXE”).

That creates an object to manipulate: it’s a window called Form1. You see it on the screen.

On the screen’s right side, you should see a line saying:

AutoRedraw      False

(If you don’t see that line, make it appear by pressing the F4 key.)

Click “AutoRedraw” then press the T key, so that line becomes:

AutoRedraw    True

That tells the computer to automatically redraw Form1 each time its contents change. (If you forget to set AutoRedraw to True, the examples in this chapter won’t work!)

Double-click in the middle of the Form1 window. The double-clicking tells the computer you want to write a subroutine about that object.

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

Private Sub Form_Load()

 

End Sub

The top line, which is “Private Sub Form_Load()”, is the subroutine’s header. The bottom line, which is “End Sub”, is the subroutine’s footer; it marks the end of the subroutine. Between those lines, insert lines that tell the computer what to do to the object (which is the Form1 window). The lines you insert are called the subroutine’s body.

Simplest example Let’s make the Form1 window show the answer to this math problem: 4 + 2. To do that, type this line —

Print 4 + 2

so the subroutine becomes:

Private Sub Form_Load()

Print 4 + 2

End Sub

To run your program, press the F5 key. Then you see the Form1 window again. In that window, the computer has printed the answer:

 6

When you’ve finished admiring that answer, stop the program by clicking the Form1 window’s X button. Then you see the subroutine again:

Private Sub Form_Load()

Print 4 + 2

End Sub

Edited example Let’s edit that subroutine, so instead of printing the answer to 4 + 2, it will print the answer to 79 + 2.

To do that, change the 4 to 79. Here’s how: click the 4’s left edge, then press the DELETE key (to delete the 4), then type 79, so the subroutine looks like this:

Private Sub Form_Load()

Print 79 + 2

End Sub

Run that program by pressing the F5 key. Then the Form1 window shows the new answer:

81

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

Longer example Let’s make the computer print the answer to 7 - 3 (which is 4) and the answer to -26.3 + 1 (which is -25.3).

To do that, change the subroutine to this:

Private Sub Form_Load()

Print 7 - 3

Print -26.3 + 1

End Sub

To make those changes, use your mouse and keyboard (as if you’re doing word processing). If you want to delete a whole line (yank it), do this: click in the line’s middle; then while holding down the Ctrl key, tap the Y key. If you want to insert an extra line, choose one of these methods:

Method 1: click at the previous line’s end, then press ENTER.

Method 2: look at the line below; click the left edge of that line’s first character; press ENTER then ­.

If you make a mistake, undo it by clicking the Undo button (which is near the screen’s top, under the word “Query”.)

When typing the minus sign, make sure you hold down the SHIFT key.

Run that program by pressing the F5 key. Then the Form1 window shows the new answers:

 4

-25.3

Your own examples Go ahead! Try changing the subroutine, to do different math problems instead!

Multiply To multiply, use an asterisk. So to multiply 2 by 6, type this:

Print 2 * 6

The computer will print:

 12

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

Print 8 / 4

The computer will print:

 2

Congratulations You’ve written VB subroutines and created a VB programs, so you’ve become a VB programmer! You can put on your résumé, “VB programmer!”

Type faster

Here are tricks that let you type faster.

You don’t need to capitalize computer words such as “Print”. The computer will capitalize them automatically when you press ENTER at the end of the line.

You must put a black space after the word “Print” to separate “Print” from the number after it. But you don’t need to put spaces around symbols such as “+”. The computer will insert those spaces automatically when you press ENTER at the end of the line.

Instead of typing the word “Print”, you can type a question mark. When you press the ENTER key at the end of the line, the computer will automatically turn the question mark into “Print” and put a space after it. So instead of typing —

Print 4 + 2

you can type:

?4+2


Huge and tiny numbers

When dealing with huge and tiny number, be careful!

Avoid commas Do not put commas in big numbers. To write four million, do not write 4,000,000; instead, write 4000000.

The symbol # If you type a whole number that’s huge (bigger than 2147483647) or a type “a decimal point followed by just 0 or nothing” (as in 53.0 or 53.), the computer will automatically write the symbol # afterwards (when you press ENTER or run the program). That’s the computer’s way of reminding itself to treat your bizarre number carefully!

Use decimals for big answers The computer sometimes has difficulty handling answers bigger than 32 thousand. To avoid difficulty, put a decimal point in any problem whose answer might be bigger than 32 thousand.

For example, suppose you want the computer to multiply 250 by 200. Since the answer to that problem is 50 thousand, which is bigger than 32 thousand, you should put a decimal point in that problem, like this —

Print 250 * 200.0

or like this:

Print 250 * 200.

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

Print 250 * 200

the computer will complain by saying:

Run-time error '6':

 

Overflow

Whenever the computer says “Run-time error”, you have two popular choices:

The simplest choice is to click “End”. You see the subroutine again. Fix the error (by putting a decimal point after the 200), then press F5 to rerun the program.

Another choice is to click “Debug”. You see the subroutine again, with a yellow arrow pointing to the bad line, which is highlighted in yellow. Fix the error (by putting a decimal point after the 200). Then press F5 to run the program from where you left off, at the fixed line (or press SHIFT with F5 to run the program from the beginning).

Then the computer will print the correct answer:

 50000

E notation If the computer’s answer is huge (at least a quadrillion, which is 1000000000000000) or tiny (less than .1), the computer might print an E in the answer. The E means “move the decimal point”.

For example, suppose the computer says the answer to a problem is:

 1.586743E+15

The E means, “move the decimal point”. The plus sign means, “towards the right”. Altogether, the E+15 means, “move the decimal point towards the right, 15 places.” So look at 1.586743, and move the decimal point towards the right, 15 places; you get 1586743000000000.

So when the computer says the answer is 1.586743E+15, the computer really means the answer is 1586743000000000, approximately. The exact answer might be 1586743000000000.2 or 1586743000000000.79 or some similar number, but the computer prints just an approximation.

Suppose your computer says the answer to a problem is:

 9.23E-06

After the E, the minus sign means, “towards the left”. So look at 9.23, and move the decimal point towards the left, 6 places. You get:

.00000923

So when the computer says the answer is 9.23E-06, the computer really means the answer is:

.00000923

You’ll see E notation rarely: the computer uses it just if an answer is huge (at least a quadrillion) or tiny (tinier than .01). But when the computer does use E notation, remember to move the decimal point!

The highest number The highest number the computer can handle well is about 1E308, which is 1 followed by 308 zeros. If you try to go much higher, the computer will gripe (by saying “Overflow”).

The tiniest decimal The tiniest decimal the computer can handle accurately is 1E-309 (which is a decimal point followed by 309 digits, 308 of which are zeros). If you try to go tinier, the computer will either say 0 or give you a rough approximation.

Order of operations

What does “2 plus 3 times 4” mean? The answer depends on who you ask.

To a clerk, it means “start with 2 plus 3, then multiply by 4”; that makes 5 times 4, which is 20. But to a scientist, “2 plus 3 times 4” means something different: it means “2 plus three fours”, which is 2 + 4 + 4 + 4, which is 14.

Since computers were invented by scientists, computers think like scientists. If you type —

Print 2 + 3 * 4

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

 14

The computer will not print the clerk’s answer, which is 20. So if you’re a clerk, tough luck!

Scientists and computers follow this rule: do multiplication and division before addition and subtraction. So if you type —

Print 2 + 3 * 4

the computer begins by hunting for multiplication and division. When it finds the multiplication sign between the 3 and the 4, it multiplies 3 by 4 and gets 12, like this:

Print 2 + 3 * 4

 

            12

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

For another example, suppose you type: