Visual Basic/Getting Started< Visual Basic
The very simplest program in VB is this:
Public Sub Main() MsgBox("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.
- Open VB's Project menu and click Add Module
- Copy or type the Main subroutine shown above into the new code module.
- Go to VB's Project menu again and click the Project1 Properties item (it should be the last item in the menu).
- In the Project Properties dialog box you should find a dropdown list labeled Startup Object, click there and choose Sub Main
- Go to the Run menu and click Start (or press F5) to run the program. VB might ask if you want to save, just say no this time.
The running program will show the words Hello World! in a small message window.
The Visual Basic Integrated Development EnvironmentEdit
The Visual Basic Integrated Development Environment (IDE) is a program from Microsoft used to create, test, and deploy Visual Basic (VB) programs. VB programs can be written using other text editors, which must then be converted to executable code (compiled and linked) by the programmer. The VB IDE allows a programmer to write code and test it immediately, converting the source program to executable code as needed (on the fly). As the name implies, creation, editing, compiling, and linking are all integrated in this development environment.
The top of the IDE window shows VB's menu bar (see screenshot). Common menu categories (File, Edit, Help, etc.) as well as items specific to creating code (Project, Debug, Run) provide the text interface for the IDE. Commonly used menu items are provided as toolbar buttons directly below the menu bar.
Two parts of creating a program; designing the user interface using forms and controls, and writing the source code; take up the majority of space in the IDE. As initially configured, four dockable windows also appear in the IDE's application space; the Project Explorer, Properties Window, Form Layout Window, and Toolbox. These and other supplied windows may be floated above the IDE, or docked to the sides, top, or bottom of the IDE application space as may be convenient for the programmer. Clicking on the title bar of a dockable window and dragging it around will dock, or undock, the window at will.
VB programs are divided into two views, the visual design of the user interface, and the code editors. The visual interface is created by adding controls from the Toolbox to the Form Layout Window. To add a control to a form; click on the desired control in the Toolbox and then click and drag its bounding rectangle on the representation of the Form in the Form Layout Window. When you release the mouse button after the click and drag operation, the selected control will appear on the form.
Clicking on a control, or the form, in the Form Layout Window highlights the control (or form) with sizing handles. You can use the sizing handles to change the Left, Top, Height, and Width properties of a control or the Height and Width properties of a form. A highlighted control can be dragged to other positions on the form simply by clicking on the control and dragging it into place. A highlighted control can also be copy and pasted to reproduce additional identical controls on the form. Clicking and dragging around multiple controls (a lasso operation) will highlight them all as a group, which can then be moved as a group, or copy and pasted as a group, as may be needed.
Code editing is done using the code module windows. The title text of a code module window shows the project and module name. Two dropdown lists show the objects accessible to that module (General) and the subroutines (Declarations) associated with the selected object in the General list. In a form's code module, the General list will list all of the controls that have been placed on the form. Each control has its own set of events and methods, which will populate the Declarations list upon selection of any control. These two windows combined help the programmer locate specific code for events and methods in the program. In small programs, the editors can be scrolled up and down to find a desired routine to work on. In large programs finding the right spot can be much more difficult, where these two lists bring the programmer to the desired location using a few clicks of the mouse.
The code editors will show the program as one long text document, or it can show the program a single routine at a time. The two buttons in the lower left of the code module window allow the programmer to set his/her view preference.
The code editors can be split into two views by moving the small bar in the upper right of the editing area. The two views show two different views of the same code module. Again, in larger programs, it may be helpful to see one section of the code in the module while working on another area of the code in the module. The split view mode allows the programmer to keep one section of the code in view while creating a new method or function.
VB Project FilesEdit
Code modules and forms are saved individually as text documents in the project folder. The filename extension (.xxx) is used to identify which type of module the file contains. The project file (.vbp) describes the project as a whole, naming the individual files needed to create the program. With VB installed correctly, double clicking on a project file will bring the entire project into a new instance of the VB IDE, while double clicking on a form (.frm) or module (.bas) or class (.cls) or control (.ctl) file will load that individual file into a new instance of the IDE. Typically, loading a single file from a multi file project (other than the project file) will not have all the information required to allow the program to run. However, in many cases, short test code, code written to test out some small idea, is best kept in its own module (and file) where it can be loaded and discarded at will. Such code can be added, removed, or edited, until it is perfected (debugged) and copied into the real program modules.
While testing a program for correctness (usually called debugging) it is often advantageous to see interim results in a calculation, or to check on values being passed to a subroutine. Setting breakpoints to stop the program at specific lines can help, as can sending printed values to a second window. VB provides a dockable window for text called the Immediate Window. It is available under the View menu or you can press CTRL+G to bring it into view. It is called the Immediate Window because it can be used to execute BASIC commands immediately. For example:
Print Atn(1) * 4
When you type that line into the Immediate Window and press Enter, VB interprets that line as a VB command and executes the command. In this case it prints the number 3.14159265358979 on the line following the command. (For expediency, the question mark can be substituted for the Print command in most circumstances.)
You can send text to that same window from a running program using the Print method of the Debug object:
Private Sub Text1_KeyPress(KeyAscii As Integer) Debug.Print Chr(KeyAscii), KeyAscii End Sub
In this case, with a Textbox called Text1 on some form, every letter a user enters into the textbox will be echoed to the Immediate Window, as well as its numerical ASCII value.
Because text is sent to the Immediate Window using the Debug object, many people refer to the Immediate Window as the Debug Window. You may find it listed either way in this literature.
It should be noted that running a program using the VB IDE is not identical to running a stand alone executable program. The program running inside the IDE is running as a sub-process of the IDE. There are a few small connection and timing issues associated with running as a sub-process. On the whole, however, a program run in the IDE will look and feel like the finished program, but to fully test a program as the user will see it, it is advisable to create the program executable (.exe) and test that for correctness and usability.
Parts of a Visual Basic ProgramEdit
A form is a window where controls are placed for use by the user of the program. The .Caption property changes the text on the title bar of the window, and the .MinButton and .MaxButton properties show or hide the minimize and maximize buttons. Different window styles such as Dialog boxes, ToolWindows, and standard Forms; as well as some allowed user actions such as resizing and minimizing; are controled by the form's .BorderStyle property. It is a common practice to name a form with frm<FormName> (ex: frmMain, or frmAlert).
A component is an executable module stored either as a .VBX file (Visual Basic eXtension for the 16-bit versions of VB), .OCX (OLE Control eXtension for 32-bit versions) file or as a .DLL (Dynamic Link Library) file. Components are pre-compiled code modules used by other program writers with/without knowledge and understanding of the details of its inner workings. Pre-compiled components provide reuseable code that has already been written and debugged. Components can be code only (.DLL) or have a visual component that can be placed on a form (.VBX and .OCX). VB supplies many commonly used components (Button, Textbox, Listbox, etc.) as controls in the Toolbox.
An event is an activity that occurs during a program's execution usually in response to the user's actions, such as a mouse click or a keypress. An event causes a procedure to execute. You the programmer can decide what code (if any) you want to place within the different event procedures.
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 and contains all the names of the editable properties as well as their current values. Some control properties are only editable while the program is running, some are only editable while in design mode.
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.
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 the name of the control, it can be set to anything including "" (or nothing). Text box names are prefixed with txt, eg; txt<BoxName>.
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 named like lbl<LabelName>.
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. Add a timer to the form and give it a name.
2. Set the time interval in the Properties window to some value above 0.
3. Double click the timer and add the code you want executed at the set intervals.
Timers have very few properties too.
This is a possible use of timer: (To see it in action add a Command button, Shape control, and Timer to a new form. Then set the Timer.Interval property using the Properties window. Copy the code below into the form's code module and press F5 to run the program.)
Private Sub Command1_Click() Timer1.Enabled = Not Timer1.Enabled End Sub Private Sub Timer1_Timer() Shape1.Visible = Not Shape1.Visible End Sub
This would make the command button stop and start the flashing (repeatedly disappear and reappear) of the Shape control. The flash interval is determined by the Timer's Interval property. Timer.Interval is measured in milliseconds.
Here is another timer example of a counter:
'***************************************************************** * '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 : 'firstname.lastname@example.org * * 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
VB Timers are given low priority on the processing totempole. If any other code needs to execute when the timed interval has elapsed, that other code is allowed to execute before the timer's procedure is called. Other code can yield some of their processing time to Windows by using the DoEvents command. That is the only VB command that will allow code you write to yield time to any pending timer events in the program. Without the use of DoEvents, each subroutine or function is executed start to finish, in serial fashion. In other words, only one command or statement can be executed at a time. Each subroutine or function must list the proper commands to execute, in their proper order.
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.
VB extends some common properties to all controls placed on a form. Name, Top, Left, and Tag, are a few of the extended property names. When you lasso and highlight several controls on a form, you can change the general property values of all the highlighted controls using the Properties window. Making a change there will change the property of the same name for all of the highlighted controls.
Reference is a kind of link that is used by Visual Basic. The word reference is used in two distinct ways:
- Component reference
- Are typically external libraries such as DLLs, OCXs, or type library. Component references are added to the project, so that all parts of the program may interact with the outside component.
- Object reference
- Is typically a pointer to an internal object. Object references differentiate, or identify, specific objects within the program. The term object is a very general term used to indicate just about anything that has properties to set, or methods to call. For example, if your form has 5 textboxes on it and you want to put text in just one of them, you need to use the proper 'object reference' to address that specific textbox.
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. In both cases, accessing the properties (or methods) of a component or object reference requires a special syntax that includes a period to separate the object and property. The syntax is: <object>.<property> or, by example: Form1.Caption = "This", or Text1.Text = "That", etc. where Form1 or Text1 are the specific objects you want to alter, and Caption or Text are the specfic properties being changed.
You can create components in VB to be used by other programs (not just those written in VB).
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 Beep Call Close Command Date Do End Error Event Exit False For Function Get GoTo If Input Kill Let Load Loop Me Name Next Not Nothing On Option Or Print Private Public Put Reset Resume Set Step Stop Sub Then Time True Until While With
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 line of code it will not execute! REM x=5
An apostrophe is most often used due to the comparative reduction in space and time as REM has been included so as to be backward compatible with earlier versions of BASIC. The REM statement is a basic command and must be preceded by a colon if following other commands on the same line. An apostrophe needs no colon:
x = 5 'This comment will work y = 3: REM and this comment will work. z = 1 REM This line would cause a syntax error.
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 interpret 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 ErrorHappened 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 ErrorHappened: 'Informs the user an error happened. 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 ErrorHappened will skip everything from i = 1 / 0 to Exit Sub if any run-time error occurs within this procedure. When an error is detected the program will continue to run from right after ErrorHappened:, 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".
ErrorHappened is just a line label, you can name it anything you wish to identify that section of the procedure you want to execute when an error happens. On Error Goto can only reference line labels that are within the current procedure. You cannot (easily) define one error handler for all procedures. 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. Ignoring errors is not a good idea in most scenarios, but in some cases the proper way to handle an error is to do nothing, so they might as well be ignored. Even using Resume Next, you can test the Err object (Err.Number) to see if an error happened on preceding lines.
See Errors for more detail about error handling.
Declaring Variables (Dimensioning)Edit
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 matrices. 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. Matrices are dimensioned almost exactly like arrays are, however, instead of the having only one dimension (1 to 20), matrices 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.
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.
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.
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.
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
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:
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:
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:
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: History||Contents||Next: Simple Arithmetic|