Search Tools Links Login

An Introduction to Visual Basic

Posted: 2002-06-01
By: ArchiveBot
Viewed: 99

Filed Under:

Visual Basic 6

No attachments for this post


This tutorial will give the beginner programmer a useful introduction to the Visual Basic compiler, the Visual Basic language, and step-by-step instructions on how to make their first program. PLEASE RATE AND LEAVE FEEDBACK! THANK YOU!

Original Author: Campbell Productions Software

Introduction to Visual Basic

By Donald Evan Campbell

Welcome to Introduction to Visual Basic! You may think that Visual Basic is hard, but it is not. It is not easy, either - it is just right. All you will need to know is in this tutorial, and you should find from this tutorial that Visual Basic can be a blast.

Table of Contents

Introduction to the Visual Basic Language

Have you ever heard of BASIC? If you have and you are familiar with its syntax, you know the core of Visual Basic already! If you don't well, then, don't worry about it. You do not (necessarily) need to know BASIC before using Visual Basic.

BASIC is a very old language that was used on mainframes in the late 80's and early 90's. It is non-graphical. Its programs look like the MSDOS prompt. Visual Basic was developed by Microsoft(c) as a graphical extension on BASIC. See the button and textbox below? These are the sort of things that you can put into your Visual Basic program. Unlike BASIC, Visual Basic programs look like a window - that is they are like the browser with which you are viewing this webpage right now.

How does Visual Basic work? Well basically, Visual Basic is Object Oriented (see the Object Oriented section). That each of the command buttons, textboxes, checkboxes, radio buttons, and dropdown boxes are treated as their own separate entities - they are objects. Think of an object - a phone. What are its properties? It is white. It is covered with buttons. It has a small LCD screen with which to tell who is calling. Look at a command button. What are its properties? It is grey. It is rectangular in shape. It says "A Command Button" on it. It can be clicked. They are treated in similar fasions, for they are both objects.

What does Visual Basic code look like? It is quite simple, really. Unlike UNIX languages like C, C++, Perl, and Python, Visual Basic requires NO semicolon, colon, or comma after each line. Each action you tell the computer to do is printed on its own line - that is if you type two instructions on one line, Visual Basic will think those two instructions are one. Look at this simple Visual Basic subroutine and see if you can tell what it does.

Private Sub CommandButton1_Click()
    Form1.Caption="Hello. How are you?"
End Sub

What does it do? Do you see the text at the top of your browser's window? That is called the caption. Form1 is your VB program's window. Form1 is an object, therefore it has properties. Caption is a property. The "." or period tells the computer that Caption is a property of Form1. If you do not understand the concept of a form, do not worry. It is explained in more detail further on in this tutorial.

When you set the program's window's caption, you are telling VB to print whatever is in quotations in the same place the caption text is located on your browser window.

If you notice, this "Sub" looks interesting. You see CommandButton1, and _Click(). If you have any programming experience, you will know that anything in parentheses "()" are arguments or values that the computer uses to perform a certain task. The _Click tells the computer to perform whatever you tell it when you click on something. The CommandButton1, as discussed above, tells the computer what object the programmer is talking about. So when will this code take place? If you guessed when you click on the object CommandButton1, you are correct! Private and Public Sub's are subroutines. Subroutines simply are little bits of code that are not part of the main routine - the main heart of your program. You must call or activate a subroutine. The Private tells the computer that this code cannot be accessed by any other application.

At this time, you should have an idea about objects, properties, setting properties, and telling the computer when to execute code. What would be the code to set a commandbutton's (named Command1) caption property to Hey. How are ya? Ya wanna go out sometime?? If you guessed Command1.Caption = "Hey. How are ya? Ya wanna go out sometime?" you are correct. Now, where would the caption appear on a command button? Look back to our example of a command button above. The caption is the statement "A Command Button."

Now for the techical stuff. There are variables in programming - this is the samethrough all languages. Variables can be declared as different types - depending on what types of data they will be holding. Variables that will be holding text are strings. Variables that will be holding integers, are integers. Variables that are holding decimals are long, and variables holding a true or false value are boolean. To declare a variable in visual basic, you can use two different methods. The Dim Statement is the most popular. It looks like this:

Dim [variable]
as Type

Where variable is the name of your variable (can be up to 255 characters), and type is the type of data the variable will be holding. You can also use the Public or Private statements. Remember: Public can be used throughout your Visual Basic program. Private can only be used in the subroutine within which you declared your variable.

Public [variable] as Type
Private [variable] as Type

Visual Basic can also handle arrays. Arrays are variables that are chopped into small blocks. Within each block you can hold a distinct value. Once again, to declare an array, you can use Dim, Private, or Public. Arrays are declared with the number of blocks into which they should be chopped in parentheses - that is [variable name]([number of blocks]). How do you use arrays? Lets say you have 10 employees in your department. Each makes a certain amount of money per hour. Instead of declaring 10 variables to keep track of your employee's salaries, you declare an array - called money, that is chopped into ten blocks. In each block, you hold an employee's hourly salary. Look at the below example to see an array declared.

Dim Salaries(10)
Salaries(0) = 20
Salaries(1) = 21

Arrays, by default, start at 0 and goto whatever number you put in the parentheses. This can be changed, though. Let's say that we need an array with blocks labeled 2 through 9. You would declare it like:

Dim VarArray(2 to 9)

If you want to put data into an array, you use the all-powerful equals sign. You get the number of the block into which you want to store your data and put that in parentheses - that is Salaries(0) - the first block. You then put an equals sign and whatever value you want to be put into this block. Remember that all strings (text) MUST BE IN QUOTATIONS!

All programming languages also have If satements. Visual Basic (VB for short) is no exception. Visual Basic's if statement can be molded, though, but it stays relatively similar through all transformations. Look at the next two examples and see how they are similar and how they are different.

If SomeVariable = 20 Then Form1.Caption = 12

If SomeVariable = 20 Then
    Form1.Caption = 12
End If

How are they the same? They do the exact same thing - if the variable SomeVariable equals 20, set the caption of form1 to 12. How are they different? The first If statement is on all one line. The second is on three. When would you use the second one over the first? Let's say that you need to check if the date is Saturday. If it is, you must do three things - set the form's caption to "Saturday", tell the user that it is Saturday, and then end the program. Going back to the statement that if more than one instruction is printed on one line, Visual Basic will treat it as one, we cannot put three different instructions on the same line as in the first If statement example above. We would need to use the second one. When you use more than one line in an if statement, you MUST end it with an End If. If you do not, then Visual Basic will think the whole application is one big if statement.

You have heard of an If, Then, Else, right? If you haven't, then an If, Then, Else statement is basically a standard if statement as described above, but with an Else clause that says: if some statement is not true, do something else. Below is the only example of an If, Then, Else statement you can use. Else's cannot be put on one line, like an if statement can.

If SomeVariable = 20 Then
    Form1.Caption = 12
Else
    Form1.Caption = 13
End If

Have you ever see a movie in, say, French, and you want to know what it means? Then someone puts subtitles on the screen? Comments are like subtitles. Comments are like subtitles. The Visual Basic compiler overlooks them - that is it knows they are not code. They are denoted by a single quote (') like this: 'This is a comment. Comments are usually written to tell a user looking at your code what is going on.

Do you know those annoying messages that pop up on your screen when your computer does something wrong? Those are called Messageboxes. You can make them in Visual Basic just to annoy anyone who is using your application. The function is MsgBox and it looks like this:

Msgbox "[What you want to say]", [buttons], "[title]"

Where "what you want to say" is the message you want in your little pop-up window, Buttons are the buttons you want on your pop-up window (vbOkOnly for an OK Button, vbOkCancel for OK and Cancel Buttons, vbYesNo for Yes and No Buttons), and title is the caption of the little pop-up window.

To test whether a user has answered yes, no, ok, or cancel to your message box, you must assign it to a variable. You can do this with:

Dim Variable
Variable = Msgbox ("Do you want to exit?", vbYesNo, "Exit, anyone?")
If Variable = vbYes then Msgbox "You Pressed Yes"

This code checks to see if the user pressed the "yes" button. Use vbNo, vbOK, vbCancel in place of vbYes to test if the user pressed the No, Ok, or Cancel buttons.

The Input box is just like the message box but it 1) requires a variable and 2) allows users to input data instead of simply outputting data to the user. Here is an example of an input box:

Dim Variable
Variable = InputBox "Enter Your Name"

This example opens a small pop-up box with a textbox in it that says Enter Your Name. When the user enters his or her name into the textbox and clicks OK, the data the user entered is stored in the variable Variable for further use.

As described before, a subroutine is not part of the main program. Therefore, it does not always run automatically. Let's say that you declared a subroutine like:

Public Sub Hello()
    Msgbox "Hello. How are you?"
End Sub

(Note the Public, and the End Sub - two NEEDED parts of a subroutine. Also note the () or empty parentheses. This subroutine takes no arguments.) This will not run at the beginning of the program. Therefore, you have to call it. To do this, use, logically enough, the call statement. You can use it thusly: Call Hello.

Loops are also an important part of Visual Basic. There are many types of loops, but we will be covering only two in this tutorial: the For Loop and the Do While loop. Here are examples of each:

Do While Counter < 100
    Msgbox "Hello. How are you?"
    Counter = Counter + 1
Loop

For Counter = 1 to 100
    Msgbox "Hello. How are you?"
Next Counter

Do you know what they do? The Do While loop only executes the message box if Counter < 100. In Do While loops, you need a line like Counter = Counter + 1 to avoid an infinite loop or a loop that simply executes for ever - to infinity. This line increases the counter's value by one each time the loop loops. Therefore, after a while, counter will be greater than 100 and the loop will end. It is a good idea, though, to initialize the counter using the equals sign like: counter = 0 before the loop starts. This tells Visual Basic where the counter should start counting at. The "Loop" at the end of this loop tells the computer to start the process over again with the new value of counter. The For loop, on the other hand, does not require a line like this. It says: Execute the message box as Counter increases its value from 1 to 100. To prevent an infinite loop, you simply put Next Counter at the end. This increases the value of counter by one each time the loop loops.

Now you should know a little about the programming language of Visual Basic. Next, you will learn how to create forms, objects, and programs using the Visual Basic compiler. Go on to the next section to continue.

The Visual Basic Compiler

This section of the tutorial will teach you the basics of the Visual Basic compiler. The Visual Basic compiler is a RAD application. No, this does not mean it is cool - it means it is a Rapid Application Development system. You can create Visual Basic applications faster than any other language because of its easy-to-use and straight-forward compiler environment.

Let's take a look at the Visual Basic compiler and its parts:

This is the New Project window. It will start EVERY TIME YOU OPEN THE VISUAL BASIC COMPILER. Visual Basic can create multiple different types of applications - Standard, ActiveX, ActiveX Controls, DLL's, Database Programs, Wizards, etc. For most Visual Basic programs you will be writing, you should select Standard EXE and Click Open. Next you will come to this screen:

This is the actual Visual Basic compiler screen. First, read each and every one of the little tags assigned to the windows. The Project Explorer is the window that lets you move through your project. A Visual Basic project consists of Modules, which house subroutines and variable declarations, Forms, which house your actual program (what the user will see when they run your program), and any other file needed for you to run your program. The Toolbox is where you find the different objects. Some objects include Command Buttons, Textboxes, radio buttons, check boxes, dropdown boxes, pictures, OLE controls, timers (which act like loops), and Shapes - which are purely for decoration. The properties window lets you set properties for objects. Remember from the beginning of this tutorial that Caption is a property? Do you see the Caption property in the Properties window? Setting this is the same as saying Form1.Caption = "something." To set the properties of a certain object, simply click on the object you want edit and insert a value for that property. The Form is the actual project. Think of this as a sketching pad. This is where you will be putting your objects.

Your First Program

Now, let's open the Visual Basic compiler and make your first program. In some computer lingos, the first program is normally a "HelloWorld" program, where the programmer is taught basic Input and Output (keyboard and monitor) operations (in our case, the command button, the message box, the input box, and the textbox.) To create your first program, follow the steps below:

See how the icon forms a crosshair? This is used to draw a commandbutton.

Click and drag to form a square the size you want your commandbutton to be. When the square is the appropriate size, let go of the mouse and the commandbutton will appear. Click on it.

In the properties window (F4 to make it appear,) goto the Caption property. Set it to "HelloWorld." Also, note the value of the Name property for this commandbutton.

Double-Click on your commandbutton. The Code window will appear. Below is a picture of the code window. Under it are the explanations for the various parts of the code window. You should become very familiar with these.

OBJECT: this is object with which the code is associated. Because you have just double-clicked on the commandbutton, which is by default named Command1, the code you type into this window will be associated with your commandbutton (Command1.) EVENT: this is a drop-down box. It lets you select at what time you want your code to be executed. Let's say that you want to display a messagebox with "Hello" in it when the user rests his cursor over object Command1. You would double-click on Command1 and select from this drop-down box the event MouseOver.

Now to start. You have just double-clicked on your commandbutton. Its default event is _Click(), which tells the computer to execute your code when someone clicks on the commandbutton. In this program, you will ask the user his/her name with an inputbox, then say "Hello" and the person's name in a messagebox. You want all of this to happen when the user clicks on your command button. Make sure that Private Sub Command1_Click() appears somewhere on the screen.

Under this line, but above the line End Sub, type in the following code:

Dim Name as String
Name = InputBox("What is your name?")
Msgbox "Hello " & Name

Note the ampersand (&.) This tells Visual Basic that you want to add something to something. In this case, you want to add the person's name to the line "Hello." If you were working with numbers and wanted to add them together arithmatically, you would use the + sign, not the ampersand (&.)

Now, run the program (hit F5.) Click on the commandbutton. Does a window with a textbox appear that says: "What is your name?"

If so, enter your name and Click OK.

Does a messagebox appear saying "Hello Jane" (if your name is Jane)? If so, you have written your first Visual Basic program! Congradulations!

Where to Go From Here

Really, you can go endless places. The best way to teach yourself is to read more tutorials, and just take maybe an hour or so each week (at the bare minimum) to try different snippets of code. If anyone gives you code, try it out, go through it, learn what it does, and try to replicate it in a BRAND NEW VISUAL BASIC STANDARD EXE FILE.

Also, try a variety of VB code. VB can offer:


Comments on this post

No comments have been added for this post.

You must be logged in to make a comment.