Visual Basic/Getting Started
From Wikibooks, the open-content textbooks collection
Contents |
[edit] Hello World
The very simplest program in VB is this:
Public Sub Main() Debug.Print "Hello World" End Sub
To create this do as follows:
- start VB
- A New Project window will appear. Select Standard.exe and click on Open.
- Go to the Project menu and click Add Module
- Copy the subroutine into the module.
- Go to the Project menu again and click the Properties entry (should be last item in the menu).
- In the dialog box you should find a combo box called Startup Object, click there and choose Sub Main
- On the View menu click Immediate Window or press Control-G, a window should open at the bottom of the VB IDE. this is usually known as the Debug Window
- Go to the Run menu and click Start with Full Compile. VB might ask if you want to save, just say no this time.
You should see the words Hello World! printed in the Immediate Window
[edit] Overview of the Visual Basic Integrated Development Environment
To follow this section, do not delete your Hello World example or this won't work.
One of the first things you'll want to learn is the use of picture boxes and the print command.
To make a picture box, just select its icon from the tool bar and click and drag one into existence where you want it to be placed on your form. i.e. click on the form, and drag on the form.
The print command is used primarily with picture boxes. It is a simple way to give the user output. Output can be given to the user at any time during the running of the program.
Before a print command runs, however, it needs something to trigger it to run, eg, clicking on a command button.
A command button is just like a picture box: after selecting its button in the tool box, just click and drag one to where you would like the command button to be placed on your form.
After creating a command button, place code inside the button, by double clicking it, to bring up a white screen, which has some text on it.
You should see something that says "Private sub command1_click()" and then lower see some text saying "End Sub".
Any (additional) code you put between those lines will run each time the command button is clicked.
Now, for the print command. Simply type picture1.print "Your message here". The picture1 refers to what object you are printing on, which is the default name for a picture box.
You can change the name of your picture box, but that will be covered later. Print is the command, but this does NOT involve a printer. It merely prints something on the screen. And the text in quotes is whatever you want your message to be.
You will need to go back to the Project menu and select Project1 Properties and select Form1 in the Startup Object drop down box which was changed in the first example.
Congratulations, you've made your first program. To test it, press the run button at the top of your screen. It looks like a 'Play' button on a VCR, and should be next to a "Pause" symbol.
Your form should pop up onto your screen, but this time when you click the command button, the code will run.
In the picture box you should see your message. If an error message appears, check your syntax or check the error guide. If you're still confused, read the printing section.
[edit] Control Properties
To display the Control Properties window, select View\Properties Window or press the F4 key. The Properties window initially appears on the right edge of the main window (see screen shot.)
[edit] Components
A component is an executable module stored either as a VBX file (for the 16-bit versions of VB) or as a Dynamic Link Library (DLL) file with the extension .OCX, which can be used by others without knowledge or understanding of the details of its inner workings.
[edit] Events
An event is an activity that occurs during a program's execution, such as a mouse click or a keystroke. An event causes a procedure to execute. You the programmer can decide what code you want to place within the procedure.
[edit] Forms
A form is a window where controls are placed upon. The .Caption property changes the title of the window, and .MinBox and .MaxBox show or hide the minimize and maximize buttons. Typing in with this is the FormBorderStyle property which determines whether the window can be resized or whether it has a title-bar. It is a good idea to name a form with frm<FormName>.
[edit] Buttons
A button will be your best friend in Visual Basic. Each button should contain code, which is added by you, the programmer. Upon clicking the button, the user will be instructing the program to execute that portion of code. For example, you could set it so when pressed, the program will make a message box that says "HELLO!". Good programming styles generally use cmd<ButtonName> when naming a button.
[edit] Text boxes
Text boxes allows the users to add text areas to their programs. This text does not have to be typed in directly by the programmer, but could come from other sources such as database fields, text files or data the user will type in while the program is running. Although the default value for this is ".Text" it can be set to anything including "" (or nothing). Text boxes are usually denoted with txt<BoxName>.
[edit] Labels
Labels are one of the most used Visual Basic objects. They are often used to label other controls (textboxes, images etc) or provide feedback to the user. They are usually marked with lbl<LabelName>.
[edit] Timers
Timers are interesting and easy to learn. If you want the program to perform a certain task after a certain amount of time, the Timer is there to help you out. Their only event procedure is _timer, which will be executed every time after a certain amount of time is passed. The most common steps to use Timers is as simple as follows:
1. draw a timer and give it a name.
2. set the time interval.
3. double click the timer and write down what you want it to do.
Timers have very few properties too.
This is a possible use of timer:
Private Sub start_Click() Timer1.Enabled = True Shape1.Visible = False End Sub Private Sub Timer1_Timer() Shape1.Visible = True Timer1.Enabled = False End Sub
This would make a shape disappear when the start button is pressed, then reappear after the interval is set in the timer's properties. Here is a timer Clock code:
Here is a timer code
'***************************************************************** * 'APRON TUTORIAL PRESENTED BY MORROWLAND * '***************************************************************** * 'Project Name : Timer * * Project Description : Using Timer and 'Counter * * Project Type : Visual Basic * * Author : Ronny André 'Reierstad * * Web Page : www.morrowland.com * * E-Mail : 'apron@morrowland.com * * Version : English (UK) * * Date : '27.06.2002 * '***************************************************************** 'Timers are the backbone in any good application, you will be able 'to decide when things will happen in millisecounds by using timers 'and counters you gain control 'declare counter as integer Dim counter As Integer Private Sub Form_Load() Timer1.Enabled = False 'disable timer at startup End Sub Private Sub Command1_Click() Timer1.Enabled = True 'starts the timer by enabling it End Sub Private Sub Command2_Click() Timer1.Enabled = False 'stops the timer by disabling it End Sub Private Sub Command3_Click() counter = 0 'reset the counter End Sub 'The timer procedure 'the timer procedure will loop in the interval of the timer 'I have set the timer interval in the "properties" menu to 1000 ms (1 sec) Private Sub Timer1_Timer() counter = counter + 1 'we set the counter to count here Text1.Text = counter 'write the counter value out as text End Sub
[edit] Picture boxes
Although called picture boxes, these objects are not just a heavyweight version of image boxes: picture boxes almost have the same properties and function as Form objects. It can do far more than just displaying pictures. Probably the best way to describe picture boxes is that they are containers that can group other objects together, kind of similar to frame objects. E.g. several command buttons can be drawn "inside" of it.
See also Simple Graphics.
[edit] General properties
General properties depend on the Object in question. Common properties include: Name, which is the file name; Background color, self explanatory; and if the object was say a timer this is where you would set how long it counted. Most general properties can be set at run time.
[edit] References
Reference is a kind of link that is used by Visual Basic. The word reference is used in two distinct ways:
- Component reference
- this connects your program to external libraries such as DLLs, OCXs, or type library
- Object reference
- an object reference is a pointer to an object
These two uses are quite distinct and generally do not cause any problems. Usually when object reference is meant it will be written out in full whereas just references usually means references to an external library.
You can create components in VB to be used by other programs (not just those written in VB).
[edit] Reserved Words
Visual Basic contains several reserved words. These words are "reserved" because they are specific functions and commands in Visual Basic. For example, a variable may not be named "Print" because it is a feature in VB to print. This can be avoided however, by naming your variables "prnt" or "print1". As long as it is not the exact word, it should work. A list of frequently used reserved words/keywords:
And As Call Do Exit False True For Function GoTo If Loop Me Next Not Nothing Option Or Private Public Resume Step Sub Then Until While If..Else..ElseIf..Then
[edit] REMs
While programming you may find it necessary to leave yourself notes. This can be used to easily identify areas of code, or as a reminder of sections of code with logic errors that need to be fixed. REMs are very simple. Merely place an apostrophe, " ' ", or the word, "REM", before the line and that line will be ignored by the interpreter, whether it be a message to yourself or a section of code. For example:
' I leave notes to myself REM or I could do it like this 'If I REM a section of code it will not execute! REM x=5
An apostrophe is most often used due to the comparative reduction in space and time. "REM"'s will almost work in exactly the same way as the apostrophe, except that a "REM" must be placed at the beginning of a line, while the apostrophe can go anywhere:
x=5 'this comment will work x=5 rem this won't
[edit] Error Checking
These are several common types of errors that one might get from a VB program:
- run-time errors
- This type of error are errors that are raised when the program is running. Examples: dividing anything by zero or assigning a string to a numeric variable.
- compile errors
- Compile errors are errors that the IDE spots at design-time and upon compiling the program just before it runs the program. These errors include syntax errors -- the error raised when the computer does not understand your code, and also errors like undeclared variables etc.
- logic errors
- Logic errors are errors that the computer cannot spot. These are errors that, even though the program runs, the result is not what you intended.
The first two of these errors are generally easy to spot, and the debugging tool can be used to high-light the line of text at which the error occurred. For example, if you wanted to make a program to convert Celsius to Fahrenheit, and in the code you used a multiplication symbol instead of division, the program would run fine, but the program would not convert the temperatures correctly, as you desired. Although sometimes these logic errors can be easy to spot, some are quite difficult. Logic errors become concealed in the lines of code when making complex programs, such as a game. Just remember, the computer does not know what the program is supposed to do, it only knows the code. Look through the code step-by-step and think of how the computer would intepret the code.
VB won't let you just ignore syntax/compile errors. You have to fix them before you can run your program. But run-time errors, which are syntactically correct, but may cause an error if an attempt is made to execute it, can be handled to possibly prevent your program from crashing. The following example shows a very good way of handling a possible error:
Private Sub Form_Load() On Error GoTo Label1 i = 1 / 0 'This line will cause an error to be raised as anything divided by zero = infinity '... 'Some code Exit Sub 'Here the subroutine is exited if no errors occur Label1: 'Handles the error MsgBox "Error Number " & Err.Number & ":" & Err.Description End Sub
The output of this example is a message box that says "Error Number 11: Division by zero". The statement On Error Goto Label1 will skip everything from i = 1 / 0 to <yy>Exit Sub if any run-time error occurs within this procedure. And the program will continue to run from right after Label1:, where the error will be displayed so that the programmer can find out what it is and fix it. This also prevents the program from "crashing".
Label1 is just a name for a label, you can name it anything you wish although it is good programming style to denote it with lbl and then the label's given name. Exit Sub means to end the Form_Load event immediately.
So if no error occurs, a message box will NOT be called because Exit Sub will already have ended or exited our subroutine. And if an error does occur, the message box will pop up, displaying the Error Number and the Error Description.
The above example is the safest way of detecting and handling any error that takes place in the subroutine. However you can also choose to ignore errors by using "On Error Resume Next" (which means to ignore all errors), and watch for errors in a certain line of code by using "On Local Error ..."
See Errors for more detail about error handling.
[edit] Declaring Variables (Dimensioning)
If you don't already know, a variable is, by dictionary definition: a symbol (like x or y) that is used in mathematical or logical expressions to represent a variable quantity. In mathematics, common variables are: x, y, z etc, and they can "hold" values like x=1, y=3 etc. In VB, instead of x, y and z, a variable can have whatever name you want. It is often good practice, and sometimes necessary, to dimension variables. Often it is called 'dimming'. This process gives the variable its name and the type of value it will be able to hold (which will be discussed later). To dimension a variable, the code is:
Dim variablename [As Type]
Of course, the variable name could be whatever you want. The type however, is different. You have a choice of single, integer, or string. This tells the computer what type of information the variable holds. "Single" variables can hold numbers with decimal. "Integers" variables can hold whole numbers, while "String" variables holds text or a set of characters. If you don't dim a variable, the type would automatically be "Variant", which can hold almost all kinds of information. For example:
Option Explicit Dim intNumber As Integer intNumber = 31 ' This is ok intNumber = "I didn't" ' Error: type mismatch (intNumber is an integer while "I didn't" is a string)
Dimming is especially important for arrays and matrixes. For an array, next to the variable name, you enter the range of the array. For example:
Dim x(1 to 10) As Integer
Arrays will be covered more in depth later. Matrixes are dimensioned almost exactly like arrays are, however, instead of the having only one dimension (1 to 20), matrixes may have two: (1 to 20,1 to 5), or even three. Dimensioning can also be used to tell the computer that variables are public. This will be discussed later in the Scope section.
Note: If you don't dimension your variables, you might end up with many unexpected errors. It could be avoided by using the Option Explicit statement, which requires every variable to be defined; if not every variable used in the program is defined, VB raises an error: "Variable is not defined". To enable this, you just have to type Option Explicit at the very top of ALL your code in the current module. It's a very good practice to do so.
[edit] Simple output
The interaction between the user and the computer consists of both the input and output of data. The computer will not receive your commands if you don't have a mouse or keyboard which are used to input commands. And conversely, you wouldn't know what the computer is doing at all if there is no monitor or speaker which are used to output data. Therefore output is important.
[edit] Message boxes
One of the easiest form of output is message box. I'm sure you've seen a lot of message boxes in Windows. This is what the code of a normal message box should look like.
MsgBox "Hello world!"
Try it. Are you tired of the boring "hello world"? Let's make a fancier one:
MsgBox "Fatal error: Your computer will be shut down in five seconds.", vbCritical, "System"
That will creep out quite a lot of people.
[edit] Printing
Note: The word "printing" here means using the Print statement, it's not about using the printer or printing files. Printing is a fairly simple part of Visual Basic, but also essential. Printing is used to output information to the user. It proves to be a valuable troubleshooting tool. Whenever printing, you need an object to print on, followed by of course, something to print. Printing may be used with various objects, however, the most common in the picture box. For the sake of simplicity, we are assuming you renamed the picture box as "pic". In this wikibook though, print is done mainly on picture boxes and forms:
pic.Print "Hello world!!" 'Prints message on picture box Print "Hello world!!!" 'Prints message on current form
[edit] Spacing
There are various ways to alter how text is spaced when printing. The most common is the comma. A comma will go to the next print zone. Print zones are 15 characters long. You can think of it like pressing the tab key when typing something out. Remember that print zones are fixed, so if you've typed 1 letter, and then used a comma, then it will be a big space. If you type 13 characters and use a comma, it will not be a large space. For example:
Private Sub Form_Click()
Me.Print "Hello", "Next Zone"
End Sub
Several new concepts are introduced in this example. The "Form_Click" contains a block of code and it is called to run when the user clicks on the current Form(Form1). 'Me' is the same as the current form (Form1). Don't be afraid to experiment. No matter what you do in VB, its always reversible. Now, the comma isn't all that versatile. Another feature is tab. Tab will move so many spaces from the BEGINNING of the line. Followed by tab in parentheses is the amount of characters spaces. For example:
Form1.Print "Hello"; Tab(10); "Yay"
This will NOT print "yay" 10 spaces after the O of "Hello". Rather it will print 10 spaces from the beginning of the line. You may use as many tabs as you want in the same print command. Although tab is useful, sometimes it is better to space things in relation to what has already been printed. This is where the space function comes in. The syntax of space is identical to that of tab. Space will move the next printed text so many spaces over from its CURRENT location. For example:
Pic.print "Hello"; Space(10); "Yay"
This will print the first Y of "Yay" 10 spaces to the right of the O in "Hello". It is important to note, if you write:
Pic.Print "Hello" Pic.Print "Hello"
They will appear on separate lines as:
Hello Hello
This can be easily dealt with in the need of having separate print statements print on the same line. You merely have to change the code to: (note the semicolon)
Pic.Print "Hello"; Pic.Print "Hello"
This will appear as:
HelloHello
If you want to make a blank line in between the two "hello"'s, then you may simply have a blank print statement WITHOUT a semicolon. For example:
Pic.Print "Hello" Pic.Print Pic.Print "Hello"
This will print as:
Hello Hello
It is important to remember that if the first print has a semicolon at the end, often referred to as a trailing semicolon, the empty print will only reverse it, and print the second Hello on the next line, and no blank line will appear.
| Previous: Introduction | Contents | Next: Simple Arithmetic |