Visual Basic is an object-oriented programming language that uses the Microsoft Windows platform. The programs that are created using Visual Basic will look and act like standard Windows programs. Visual Basic provides one the tools to create windows with elements such as menus, text boxes, command buttons, option buttons, list boxes and scroll bars.
This tutorial does not completely cover all aspects of Visual Basic. This is just basically an overview to get a beginner to the language up to pace. Databases, Crystal Reports and others are not included to keep this tutorial under 500 pages and to keep carpal tunnel from occurring.
Although this tutorial is aimed at beginners, it was also written assuming that the reader possibly has some programming knowledge. For instance: what an IF / THEN / ELSE statement is, For / Next loop and so on. If you have taken Basic or QBasic, that
Labels, Text Boxes and Command Buttons
Label - A control that is used to display text as a caption. Labels cannot be altered by the user. They are simply used to display headings and are a result of processing, as well as other information on a form. Labels begin with a lbl prefix.
Examples of labels:
Text Box - Control that is used to enter information onto a form. Text boxes can have focus, and are the primary means of providing input to a project in Visual Basic. Text boxes begin with the prefix of txt
Examples of Text Boxes:
Command Buttons - Control that is used to activate a procedure. When a command button is clicked or activated using an access key, an event will take place (the code behind the command button is executed.) Command buttons begin with the prefix cmd
Types of Errors
Special Functions and Methods
VAL - A function that will convert a string to a numeric value. It will begin with the far left character of the string. If that character is a numeric digit, decimal point or sign, VAL will convert the character to a numeric value, and continue to the next character. Once a non-numeric character is found, the VAL function will stop.
PrintForm - A method that will print the current form on the printer. This is executed during run-time.
FORMAT - This is used to format a variable. Variables can be formatted as fixed numbers, currency and percents.
FormatCurrency - This function will take a number and format it as currency with two decimal places and a $ sign. There is only one argument, the number you want to format.
FormatNumber - This function will format a number as a decimal with a set number of decimal places. The first argument is the number you want to format. The second is the number of decimal places you want the number to have.
FormatPercent - This function will take the number, and format it as a percent by multiplying the number by 100 and adding a percent sign to the end. By default, the number will be rounded to zero decimal places unless you specify a second argument.
FormatDate and Time - This function will take a string and format it as a Date, Time or both. The first argument is the date or time to be formatted. The second argument is the format of date/time you decide to use.
Variables and Constants
Option Explicit - A statement that will force you to declare all variables used in your program. If you fail to declare a variable, an error will occur when you run your program.
DECLARING A VARIABLE:
When you declare a variable, VB reserves space in the computers memory and assigns a name to it. When declaring variables, certain rules must be followed.
Rules for Variable Names:
NOTE: The rules specified above also apply to control names placed on a form.
The DIM statement is used to declare all variables in VB.
DIM < variable_name > as < datatype >
DECLARING A CONSTANT:
Constants are always declared using the keyword CONST. You give the constant a name, data type and value. Once a value is declared as a constant, it can never be changed again in the program. Trying to change a constant will cause an error. The rules for variables also apply to constants.
DIM < constant name > as < datatype > = <value >
NAMED CONSTANTS - These are constants that you name yourself with the CONST keyword. Named constants can come in the form of numeric constants and string constants.
NUMERIC CONSTANTS - Constants that can contain only the digits 0-9, a decimal point.
STRING CONSTANTS - Constants that can contain letters, digits, and special characters such as @#$%^&*. String constants must be enclosed in double quotes.
INSTRINCT CONSTANTS - System-Defined constants that are built into VB.
Examples of Instrinct Constants:
SCOPES OF VARIABLES:
Scope - Is a term used to refer to the visibility of a variable.
Lifetime - The period of time that variables exist within the program.
3 LEVELS OF SCOPE:
Default Property - Automatically selects a command button when the user presses the < ENTER > key. To make a command button a default button, you set its DEFAULT property to TRUE. Only one command button per form can have its default property set to true. When the program is run, this command button will be highlighted.
Cancel Property - The button that is selected when the user presses the < ESC > key. To set a command button to cancel the program, set its CANCEL property to TRUE. Only one command button per form can have its cancel button set to true.
TabStop Property - Represents all controls on a form that can receive focus. If the TabStop property is TRUE, a control can receive focus. If it is FALSE, then it cannot.
Some controls can receive focus, others cannot.
Text Boxes, and Command Buttons can receive focus.
Labels and Images cannot receive focus.
TabIndex Property- Determines order of focus moves as the < TAB > key is pressed.
Name - Used to assign the name of the control as it is known by the project. Caption - The label that appears next to, in or on top of the control.
BackColor - The background color of the control.
ForeColor - The color of the text that appears on or next to the control.
Text - The text which appears in a text box.
Alignment - Determines the justification of text within a label or text box.
MultiLine - Allows a string to be spread out among several lines, rather than one line.
Font - Allows you to set the font and font size of a control.
TabIndex - Determines the order the focus moves as the < TAB > key is pressed.
Visible- Property used to make a control visible or invisible
FillStyle - Primarily used with shapes, is used to fill the shape. Different options are available.
Option Buttons... Formats
Option Buttons - Group of controls where only one can be selected at a time.
Check Boxes - Group of controls where more than one can be selected at a time.
Frame - Control that often acts as a container for a group of option buttons or check boxes.
Image - Type of control that is used to hold a graphic. Shape - Type of control used to place rectangles, squares, ovals and circles on a form.
The VALUE property of the option button is set TRUE if you want it to be selected, otherwise, FALSE. Set the option buttons CAPTION property to the text you want to appear next to the option button. When assigning an option button, a variable name always starts out with the prefix, opt. If you want an event to occur when you click on an option button, you can double-click on the option button from your form to enter in the code you want executed.
More than one check box can be selected at a time.
The VALUE property of the option button is set to CHECKED if you want it to be selected, otherwise, set it to UNCHECKED.
A second option is to set the VALUE property on check boxes to a 0, 1 or 2.
Set the CAPTION property to the text you would like to appear next to the check box.
When assigning a variable name, always start out with prefix chk.
If you want an event to occur when you click on a check box, double-click the button to place code behind.
Click on the images PICTURE property and locate the folder or drive where the picture is located.
All controls that are images should begin with an img prefix.
The types of shapes and codes are shown below...
All controls that are shapes should begin with the shp prefix.
Use the crosshair pointer to drag a line across the screen. You may rotate the line in any direction and stretch it until releasing the move button.
Focus - Refers to the currently selected control on the form. This can be indicated by an | - Beam, selected text, highlighted caption or dotted border. The control with focus is ready to receive input.
SetFocus - A built-in function that when executed will move the cursor to the control and give that control focus. SetFocus can be used with text boxes, command buttons, option buttons and check boxes.Examples of setFocus:
Working With Strings
Concatenation - Refers to combining two or more smaller strings into a larger string. In VB, you can either use the & or + symbols to concatenate.Examples of Concatenation:
CENTERING A FORM IN THE MIDDLE OF THE SCREEN:
(This code would go in the FORM LOAD (double click any empty space on the form.)
< Name of form > .Top = (Screen.Height - < Name of form > .Height)/2
< Name of Form > .Left = (Screen.Width - < Name of form > .Width)/2
< Name of Form > - This is the actual name of the form as you have saved it in your program.
If you named your form, "myForm" then you would code the statement in the following way:
Input Boxes, Message and List Boxes
Input Box - This is a function that will display a message, and allow the user to enter information in a text box. In the Input box, you can display a message called a prompt. The prompt will help the user decide what information he or she needs to enter in the text box.
The input box will have a text box with the prompt above it and two command buttons (OK and CANCEL). OK will accept any input the user enters, and place it in the variable on the left hand side of the equals sign. CANCEL will ignore any input entered by the user, and return back to the form currently open.
Input Boxes are often used when one wants to retrieve records from files.VariableName = InputBox("Prompt","Title")
The prompt must be enclosed in quotes. The title must also be in quotes and will appear in the Title Bar of the Input Box. If no title is entered, the title of the project will appear in the Title Bar.Input Boxes can appear in the following places:
Form_Load - Code executed as the project is loading. The first time a form is displayed in a project, VB generates an event knows as FORM_LOAD. Any code in Form Load is then executed.Things that are done in the FORM_LOAD section of a VB program include the following:
To get the FORM_LOAD event to enter code, double click on an empty area on the form. The FORM_LOAD event begins and ends with the following procedure headings:Private Sub Form_Load()
< Place Code Here >
Example of code in the FORM_LOAD event:
Message Boxes and List Boxes
Message Box - A special type of VB statement/function that displays a window in which you can display a message to a user. The message box can be a statement or function and has the name, MsgBox.The following can be displayed to the user with a Message Box:
MESSAGE BOX STATEMENT
The message box statement is designed to be on a line by itself. The syntax of the MsgBox is identified below:MsgBox < "Prompt" > , < Buttons/Icons > , < "Caption" >
Prompt - The message you want to appear in the message box.
Buttons/Icons - This determines what command buttons and/or icons that will appear on the message box (this portion is optional).
Caption - This is the caption that will appear on the title bar of the message.
MESSAGE BOX FUNCTION:
The message box function will appear on the right hand side of the equals sign. Also, if your message box is a function, you must enclose arguments in ( and ).VarName = MsgBox( < "Prompt" > , < Buttons/Icons > , < "Caption" > )
Sample code using Message Boxes:
List Box - A type of control used to hold a list of items from which the user can select one item from the list. You should use the lst prefix when naming list boxes.Items can be added to a list box in two ways.
Using the LIST property for the list control
Using the AddItem method
< object_name > .AddItem < Value >
If your values are strings, they must be enclosed in double quotes. When items are added to the list, they are given an index. The first item added to the list will have an index of zero the 2nd of one, and so forth.Example of - ADDING ITEMS TO THE LIST:
This will highlight the item "Brown". Harvard will have an index of 0, Yale of 1 and so forth.
ListIndex PROPERTY :
The listIndex property will highlight an item in the list when the program is run. Only one item can be set with the listIndex property. The format of List Index property is shown here:< control > .ListIndex = 3 'This will highlight the 4th item in the list.
This will sort the items in your list alphabetically if the SORTED property is set to TRUE. This will also re-index the items in your list. If the ListIndex property is used, the highlighted item will change.
This will empty out the contents of a list box...
< control > .Clear
This will remove one item from the list. When using RemoveItem, you must include the index of the item to remove.< control > .RemoveItem < index >
This will remove the item in the lstSchools list box with the index of 3, which is the 4th item in the list.
LstCount - The ListCount property is used to hold the number of items in the list. ListCount will always be one more than the highest element in the list.
Sub Procedures, Random Numbers
Procedure - A unit of code that performs a specific task and can be called from other locations of the program.
PURPOSES OF PROCEDURES:
TYPES OF PROCEDURES:
Sub Procedure - A procedure that performs a task but DOES NOT return values back to the calling module.
Function Procedure - A procedure that performs a task and RETURNS a value back to the calling module. With function procedures, the value is returned back to the calling module using the function name.
CREATING A NEW SUB PROCEDURE:
Example of a Sub Procedure:
Example of a Sub Procedure Call:
Example of a Function Procedure:
Example of a Function Procedure Call:
The WITH keyword allows you to cut down on coding when dealing with properties of controls.
Syntax of WITH statement:
With < control >
.< property1> = < value1 >
.< property2> = < value2 >
.< property3> = < value3 >
Assigning controls without the WITH KEYWORD:
Assigning controls using the WITH KEYWORD:
COMMON DIALOG CONTROL
Allows your project to use the dialog boxes that are provided as part of the Windows environment to set properties for a control such as font, font size and color.
FEATURES OF THE DIALOG CONTROL:
RETRIEVING THE COMMON DIALOG CONTROL:
Example Syntax for Setting Fonts:
With dlgCommon (assuming that you named it that)
.Flags = cdlCFScreenFonts
Menus, Combo Boxes and QB Color
Menu - A drop-down list of items displayed below a menu name on the screen from which you selected one item.
In both Windows and VB, a menu consists of a menu bar with menu names, each of which drops down to display a list of menu commands. You can use menu commands in place of or in addition to the command buttons to activate a procedure.
Menu commands are actually controls and have events and properties. Each menu command has a Name property and a Click event, similar to a command button. To create a menu for your form, you will use the Visual Basic Menu Editor, which accessible by pressing < CTRL > + E or Click on Menu Editor Icon.
PARTS OF THE MENU:
Caption - Holds the words you want to appear on the screen.
Name - Indicates the name of the menu control and what the control is referred to by the program. When naming, start out with the prefix, "mnu" . For example, if you had a menu control for "file", you would name it, "mnuFile"
SUBMENU - A list of commands that appear underneath a menu command, (a menu within a menu). To create a submenu, press the right arrow key to move to the next level.
Menu List Box - Shows the list of all menu items that have been created and the indication levels. You can move up, down, left and right by clicking on the name of the menu item and then clicking on one of the four arrow buttons.
Separator Bars - A horizontal line that separates one menu from another. To define a separator bar, type a single hyphen ( - ) for the caption and give it a name. Even though you can never reference the separator bar in the code, you still have to give it a name. If you have more than one separator bar, each one has to have a unique name. (mnuSep1, mnuSep2, ...ect.)
Shortcut Keys - You can create a keyboard shortcut key for a menu item when its created. Select a shortcut key for your menu item by selecting it from the list provided. The purpose of the shortcut is to provide an alternative to sorting through menus to perform a single task.
Checked - If you want a check mark to appear next to an item in your menu, you would put a check here. Check marks are normally for options that you want to be toggled on and off.
Enabled - If you want the user to be able to select a menu item, this will be checked. By default, all are enabled. If unchecked, this menu item will be dimmed out. You can also change this property in the actual code (mnuStar.Enabled = False).
Visible - Determines whether a menu item is displayed on the screen or not. If there is a check in this check box, the menu item will be displayed on the screen. If the box is not checked, the menu item will not be displayed. This property can also be changed in the actual code (mnuStar.Visible = True).
Insert - Click on this if you want to insert an item into the middle of a menu. The item will be inserted at the location of the current item. All items below that point will be moved down.
Delete - Will delete the highlighted menu. Cancel will close the menu editor without saving changes, and OK will save changes to the menu and close the menu editor.
Combo Box - A type of control used to hold a list of items from which the user selects one from a pull down menu.
Differences between a List Box and a Combo Box:
Like list boxes, items can be added to a combo box in two ways...
ADDING ITEMS TO THE LIST USING THE LIST PROPERTY:
ADDING ITEMS TO THE LIST USING THE ADDITEM PROPERTY:
< object_name > .AddItem " < Value > "
ADDING ITEMS INTO THE ItemData ARRAY:
< object_name > .AddItem " < Value > "
< object_name > .ItemData(< object_name > .NewIndex) = < Value >
ADDING ITEMS TO THE LIST:
The code below will add items into the list of a Combo Box:
Harvard will have the index of 0, Yale of 1 and so on
Entering Items into the ItemData array of a Combo Box...
The Text property refers to the actual item that is currently selected in the list.
< label > = < control > .Text
ListIndex works as the same as List Boxes. Same as NewIndex, ItemData, Sorted, Clear, RemoveItem, ListCout...ect.
When naming Combo Boxes, use the prefix, "cbo". For example, if you wanted a combo box named School, you would name it, cboSchool.
QBCOLOR - is a built-in function in VB that will display 15 different colors. The QBCOLOR function has one argument, which is the index of the color to be displayed. The index can range from values 0 to 15. What the heck, here are the values for you: