Comprehensive tutorial aimed at introducing you to the basics of programming in Visual Basic 6.0.
Getting Started
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
‘basis’ of Visual Basic. This is just basically an over view
to learn a bit about VB. Databases, Crystal Reports and others are not
included to keep this tutorial under 500 pages and to keep carpal tunnel
from occurring.
This tutorial was written assuming that you
POSSIBLY have SOME programming knowledge. Like what an IF / THEN / ELSE
statement is. So, if you have taken Basic Or Qbasic, that’s ideal
before reading this tutorial.
Also, it would not help much reading this
tutorial if you do not have VB 6.0 on your computer. I think you can download
it from Kazaa Lite (kinda big though) if you do not have it. But get it
if you don’t have it, open it and read this.
Procedural vs. Non-Procedural Languages
Procedural Languages – Programming languages that
have a set plan that you follow to execute a program. You have a series
of statements that you execute where you start with the first statement.
The statements are executed in order from beginning to end. The program
terminates after the last statement is executed.
Examples of Procedural Languages:
- FORTRAN
- COBOL
- BASIC
- C
- PASCAL
and more…
Non-Procedural Languages – Object-Oriented programming
languages that are Event-driven. Here you don’t just have a series
of statements that are executed, you have several choices of different
things you can do in a program. You select the event that you want to
occur. Only the code for that event is executed.
Examples of Procedural Languages:
- Visual Basic
- C++
- DELPHI
- JAVA
Labels, Text Boxes and
Command Buttons
Label – A control that is used to display text
as a caption. Labels cannot be altered by the used. They are simply used
to display headings and results of processing as well as other information
on a form. Labels begin with a .lbl extension.
Examples of labels:
• lblName <br>
• lblAddress <br>
• lblCity
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:
• txtSponge <br>
• txtBob <br>
• txtNum1
Command Buttons – Control used to activate a procedure.
When a command button is clicked on or activated using an access key,
and event will take place (the code behind the command button is executed.)
Command buttons begin with the prefix .cmd
Types of Errors
- Syntax Errors – Compiler errors that occur
when your project code is converted to machine language. These are errors
that occur when you violate the syntax rules of Visual Basic. VB will
highlight these errors in RED. - Run-Time Errors – Errors that occur when programming is
actually executing. These types of errors will cause the program to terminate
abnormally. Examples of run-time errors are division by zero, or trying
to do calculations with non-numeric data. VB will display a dialog box,
pull up the affected code on screen, and highlight where the error occurred
in YELLOW. - Logical Errors – Errors which allow your project to run,
but will produce incorrect results. These errors are tough to find and
debug because no error message will be displayed or highlighted. You will
have to dig through the code to find the error(s). Examples would be :
Adding 3 instead of subtracting 3, or displaying the wrong info in a label.
Special Functions and
Methods
VAL() – A function that will convert a string to
a numeric value. It begins with the left-most character of the string.
If that character is a numeric digit, decimal point or a sign, VAL will
convert the character to a numeric and move on 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.
Syntax :
<var> = FORMAT(<var>,"<type
of format>")
Examples:
lblTotal = Format(lblTotal,"Currency")
‘Formats number with a $ and two decimal places.
lblArea = Format(lblTotal,"Fixed")
‘ Formats number
as decimal with two decimal places.
LblPctTotal = Format(lblPctTotal,"Percent")
‘Formats
number as percent with two decimal places and adds % to end of number.
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.
lblSum = FormatCurrency(NumToFormat)<br>
lblTotalAmount = FormatCurrency(curTotal)
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.
lblTotal = FormatNumber(NumToFormat,NumOfDecimalPlaces)<br>
lblSum = FormatNumber(Sum,2)
FormatPercent – This function will take the number and format it
as a percent. The function will multiply by 100 and add a percent sign
to the end of the number. The number by default will be rounded to zero
decimal places unless you specify a 2nd argument.
lblTotalPct = FormatPercent(NumToFormatAsPercent)<br>
lblSumPct = FormatPercent(NumToFormatAsPercent, NumOfPlaces)<br>
lblCurrInterest = FormatPercent(CurrentInterest)
FormatDate 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 2nd argument is the format of date/time you wish to use.
lblCurrentDate = FormatDateTime(StartingDate, vbShortDate)<br>
lblCurrentDate = FormatDateTime(EndingDate, vbLongDate)<br>
lblCurrentTime = FormatDateTime(StartingTime, vbShortTime)<br>
lblCurrentTime = FormatDateTime(StartingTime, vbLongTime)
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 it a name. When declaring variables, there
are certain rules that must be followed.
RULES (for variable names):
- Variables must begin with a letter.
- Can consist of letters, digits and the underscore.
- Cannot contain any spaces or periods.
- Must be 1 to 255 positions in length
- Cannot use Reserved Words as variable names.
NOTE: Rules ( above ) also apply to naming controls that are placed
on a form.
The DIM statement is used to declare all variables in
VB.
Syntax:
DIM <variable_name> as <datatype>
Examples:
DIM inNum1 as Integer<br>
DIM strName as String<br>
DIM curTotalAmount as Currency
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
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.
Syntax:
DIM <constant name> as <datatype>
= <value>
Examples:
DIM sngPI as Single = 3.14<br>
DIM curTaxRate as Currency = .07
NAMED CONSTANTS – These are
constants that you name yourself with the CONST keyword. Named constants
can come in the form as numeric constants and string constants.
NUMERIC CONSTANTS – Constants that can contain only the digits
0-9, a decimal pt and sign.
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:
- vbRed
- vbGreen
- vbBlue
- Checked
- vbYellow
- UnChecked
SCOPES OF VARIABLES
Scope – Is a term used to refer to the visibility
of a variable.
Lifetime – The period of time that variables exist.
3 LEVELS OF SCOPE:
- Global Variable – Variable accessible anywhere
in VB, in all forms that are a part of the project. - Module-Level Variable – Variable that to all procedures
on the form in which it is declared. - Local Variable – Variable accessible only in the procedure
which it was declared.
PROPERTIES
Default Property – Automatically selects a cmd
button when the user presses the key. To make a cmd 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 cmd button will be highlighted.
Cancel Property – The button that is selected when
the user presses the key. To set a cmd button to the cancel
button, you set its CANCEL property to TRUE. Only one cmd 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 cant.
Txt Boxes, and cmd buttons can receive focus.
Labels and images cannot receive focus.
TabIndex Property – Determines order of focus moves as the
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 justification of the text within a label
or text box.
- 0 – Left Justify
- 1 – Right Justify
- 2 – Center
MultiLine – Allows a string to be spread out among
several lines instead of one line.
Font – Allows you to set the font and font size of a control.
TabIndex – Determines the order the focus moves as the
key is pressed.
Visible – Property used to make a control visible or invisible
lbl
Total.Visible = True 'label will
be displayed on the form.<br>
lblTotal.Visible = False 'label will not be displayed on the form.
FillStyle – Primarily used with shapes, is used to fill the shape. Different options are available.
0 – Solid
1 – Transparent
2 – Horizontal Line
3 – Vertical Line
4 – Upward Diagonal
5 – Downward Diagonal
6 – Cross
7 – Diagonal Cross
EXAMPLES :
<font size="3">• Square.FillStyle = 0 <br>
• Square.FillStyle = 8 </font>
Option Buttons, Check
Boxes, Images, Frames and Shapes
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.
OPTION BUTTONS:
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 opt
button, you can double-click on the opt button to place code behind the
opt button.
CHECK BOXES:
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.
- 0 – UnChecked
- 1 – Checked
- 2 – Grayed
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 chk
box, double-click the button to place code behind.
IMAGES:
Click on the images PICTURE property and locate the folder
or drive where the picture is located.
Select the pic you want and it will be placed on the form.
Set images STRECH property to TRUE. This will size the
pic to the size of the control you have defined on the form.
All controls that are images should begin with img prefix.
SHAPES:
The types of shapes and codes are shown below…
- 0 – Rectangle
- 1 – Square
- 2 – Oval
- 3 – Circle
- 4 – Rounded Rectangle
- 5 – Rounded Square
All controls that are shapes should begin with the shp prefix.
LINES
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.
All line controls should begin with the lin prefix.
Determining Focus
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 txt boxes, cmd buttons, opt buttons and chk
boxes.
Examples of setFocus:
txtNum1.setFocus '
will place cursor in the text
box.
<font size="3">
cmdCalc.setFocus
'will hilight this command button.
<font size="3">
optBlue.setFocus
‘will put dotted lines around this opt button.
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 do concatenation.
Examples of Concatenation:
StrFirstName + " " + strMiddleInitial + ".
" + StrLastName
StrFirstName & " " + strMiddleInitial & ". "
+ StrLastName
Formats
CENTERING A FORM IN THE MIDDLE OF THE SCREEN:
(This code would go in the FORM LOAD [ by double clicking
empty space on the form.])
<p><font size="3"><Name of form>.Top = (Screen.Height - <Name of
form>.Height)/2<br>
<Name of Form>.Left = (Screen.Width - <Name of form>.Width)/2</font></p>
<Name of Form> – This
is the actual name of the form as you have saved it in your program.
If you named your form SQUARE, you would code the statement
in the following way:
SQUARE.Top = (Screen.Height - SQUARE.Height)/2<br>
SQUARE.Left = (Screen.Height - SQUARE.Width)/2
Input Boxes
Input Box – 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, which will help the user decide
what information he needs to enter in the text box.
The input box will have a txt box with the prompt above
it and two command buttons, OK and CANCEL. The OK will accept whatever
input the user enters and place it in the variable on the left hand side
of the equals sign. The CANCEL button will ignore any input entered by
the user and return the user back to the form that is currently open.
Input Boxes are often used when one wants to retrieve
records from files.
VariableName = InputBox("Prompt","Title")
Examples:
StrName = InputBox("Enter your name",
"Sponge Bob")<br>
StrCareer = InputBox("Enter your workplace", "Nickelodeon")
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
- Command Buttons
- Option Buttons
- Check Boxes
Form Load
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:
- Code to center the form in the middle of the screen
- Code to initialize variables
- Code for input boxes so the user can enter info.
- Display info in labels on the form.
To get the FORM_LOAD event to enter code, again; 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>
End Sub
Example of code in the FORM_LOAD event:
Private Sub Form_Load()<br>
InputBoxes.Top = Screen.Height - InputBoxes.Height)/2<br>
InputBoxes.Left = Screen.Width - InputBoxes.Width)/2<br>
StrName = InputBox("Enter your name", " Nickelodeon Inc.")<br>
LblName = StrName<br>
End Sub
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
- Optional Icon
- Title Bar Caption
- Command Buttons
MESSAGE BOX STATEMENT
The message box statement is designed to be on a line
by itself. The syntax of the MsgBox is show here:
<font size="3">MsgBox< "Prompt">,<Buttons/Icons>,<"Caption"><br>
<br>
MsgBox "Sponge Bob is -J’s brother!",vbInformation,
"Nickelodeon Inc."<br>
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 msg box is a function, you must
enclose arguments in ( ).
VarName = MsgBox(<"Prompt">,<Buttons/Icons>,<"Caption">)
IntRes = MsgBox("Are my fingers tired?",
vbYesNo + vbQuestion,"My Question")
Sample code using Message Boxes:
Private Sub cmdCheck_Click()<br>
If val(txtNum1) > val(txtNum2) Then<br>
MsgBox "First Number is greater than second", vbInformation,
"Comparing Numbers"<br>
ElseIf val(txtNum2) > val(txtNum1) Then<br>
MsgBox "Second Number is greater than the first", vbInformation,
"Comparing Numbers"<br>
Else<br>
MsgBox "The two numbers are equal", vbInformation, "Comparing
Numbers"<br>
End If<br>
End Sub
LIST 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:
lstSchools.AddItem "Harvard"<br>
lstSchools.Additem "Yale"<br>
lstSchools.Additem "Princeton"<br>
lstSchools.Additem "Brown"<br>
lstSchools.Additem "Cornell"<br>
lstSchools.ListIndex = 3
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.
lstSchools.ListIndex = 3 'This will highlight the
4th school in lstSchools.
Sorted PROPERTY:
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.
Clear METHOD:
This will empty out the contents of a list box…
<control>.Clear</font></p>
<p><font size="3"><lstSchools.Clear
RemoveItem METHOD:
This will remove one item from the list. When using RemoveItem,
youmust include the index of the item to remove.
<control>.RemoveItem <index></font></p>
<p><font size="3">LstSchools.RemoveItem 3<br>
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, Fonts,
Color and 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:
- Breaks large sections of code into smaller units
of code that perform a specific task. - Makes it Easier to debug and maintain program.
- Cuts down on the amount of code that has to be written and eliminates
duplication of code.
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 (in VB 6.0
of course):
Display the code window for the form
Select ADD PROCEDURE from the TOOLS menu
Enter the name of the procedure in the text box next to where it says
NAME
Select PRIVATE for SCOPE
Click OK
You will be given the procedure shell. Type in the contents of your procedure
Click on the code button to exit the procedure
Example of a Sub Procedure:
Private Sub AddNumbers()<br>
Sum = val(txtNum1) + val(txtNum2)<br>
LblSum = Sum<br>
End Sub<br>
Example of a Sub Procedure Call:
Private Sub cmdCalculate_Click()<br>
AddNumbers<br>
End Sub
Example of a Function Procedure:
Private Function AddNumbers()<br>
AddNumbers = val(txtNum1) + val(txtNum2)<br>
End Function
Example of a Function Procedure Call:
Private Sub cmdCalculate_Click()<br>
LblSum = AddNumbers()<br>
End Sub<br>
WITH STATEMENT
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>
End With
Assigning controls without the WITH KEYWORD:
l
<font size="2">blEmployee.Font.Name
= dlgCommon.FontName<br>
lblEmployee.Font.Bold = dlgCommon.FontBold<br>
lblEmployee.Font.Italic = dlgCommon.FontItalic</font>
Assigning controls using the WITH KEYWORD:
With lblEmployee.Font<br>
.Name = dlgCommon.FontName<br>
.Bold = dlgCommon.FontBold<br>
.Italic = dlgCommon.FontItalic<br>
End With
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:
- You only need common dialog control on your form
- You cannot change the controls size
- The location of the control does NOT matter
- The control will be invisible when the program runs
- Dialog controls are stored with an extension of .ocx
- When naming Dialog controls, begin with a prefix of dlg
- The common dialog box may not appear in your toolbox. It is a custom
- control and will need to be added to your project before you can use
it.
RETRIEVING THE COMMON DIALOG CONTROL:
- click on Project
- click on Components
- Scroll down and find Microsoft Common Dialog Control 6.0
- Click the check box next to it to select it.
- Click OK and it will be placed in your tool box.
- Click on Dialog Control and place it on your form.
CHANGING FONTS:
Example SYNTAX of SETTING FONTS:
With dlgCommon (assuming that you named it that)
.Flags = cdlCFScreenFonts ‘Loads different fonts into memory
.ShowFont
End With
With txtName.Font<br>
.Bold = dlgCommon.FontBold<br>
.Italic = dlgCommon.FontItalic<br>
.Name = dlgCommon.FontName<br>
.Size = dlgCommon.FontSize<br>
End With
CHANGING COLOR:
Example SYNTAX of CHANGING COLOR:
<font color="#000000">dlgCommon.ShowColor 'Brings
up the color box<br>
txtName.ForeColor = dlgCommon.Color 'Applies it to the font</font>
RANDOM NUMBERS
Rnd – Generates a random number between 0 and 1.
Randomize – Tells VB to randomly generate numbers for the rnd statement.
Using randomize will allow the rnd statement to generate an entirely random
set of numbers that do not follow any recognizable pattern.
Generating Numbers between 1 and 10:
Num = Int((10 - 1 + 1)* rnd + 1)
Generating Numbers between 1 and 100:
Num = Int((100 - 10 + 1)* rnd + 1)
INT() FUNCTION:
Converts a floating point value to an integer by truncating
off any remainder that the number has. ( INT(4.656) will return a value
of 4. )
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 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 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.
)
Short Cut Keys – You can create a keyboard short cut key for
a menu item when its created. Select a short cut key for your menu item
by selecting it from the list provided. The purpose of the short cut is
to give you an alternative to going through a menu to perform a 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 BOXES
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:
- With a list box, there is no pull down menu, user
scrolls through the list using scroll bars and selects the item of his/her/OtHeR
choice. With a combo box, the user click on a down arror, a pull down
menu is displayed and the user chooses by clicking one on the list.
- You can type your own entry into the list with a combo box. With
a list box, you cannot type in your own entries.
Like list boxes, items can be added to a combo box in two ways…
- Using the List property
- Using the AddItem method
ADDING ITEMS TO THE LIST USING THE LIST PROPERTY:
1.) Scroll through the properties window to the LIST property
2.) Click on the down arror to drop down an empty list
3.) Type your first item and press
4.) Continue entering items as indicated in 3 until finished
5.) Press <ENTER> or click outside of list box to complete operation.
ADDING ITEMS TO THE LIST USING THE ADDITEM PROPERTY:
1.) Double click on the form to open FORM_LOAD
2.) Enter your items using the below format :
<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:
Puttings items into the list of a Combo Box…
cboSchool.AddItem "Harvard"<br>
cboSchool.AddItem "Yale"<br>
cboSchool.AddItem "Princeton"<br>
cboSchool.AddItem "Brown"<br>
cboSchool.AddItem "Cornell"
Harvard will have the index of 0, Yale of 1 and so on
Entering Items into the ItemData array of a Combo Box…
cboOffice.AddItem "Paper"<br>
cboOffice.ItemData(cboOffice.NewIndex) = 300<br>
cboOffice.AddItem "Cartrige"<br>
cboOffice.ItemData(cboOffice.NewIndex) = 3200<br>
cboOffice.AddItem "Folders"<br>
cboOffice.ItemData(cboOffice.NewIndex) = 250<br>
cboOffice.AddItem "Binder"<br>
cboOffice.ItemData(cboOffice.NewIndex) = 400
TEXT PROPERTY:
The Text property refers to the actual item that is currently
selected in the list.
<label> = <control>.Text
lblFood = cboFood.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.
QB COLOR
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 ya:
-Index- | -Color- |
0 | Black |
1 | Blue |
2 | Green |
3 | Cyan |
4 | Red |
5 | Magenta |
6 | Yellow |
7 | White |
8 | Gray |
9 | Light Blue |
10 | Light Green |
11 | Light Cyan |
12 | Light Red |
13 | Light Magenta |
14 | Light Yellow |
15 | Bright White |
Example:
ShpRectangle.FillColor = QBColor(1) ‘Will be
shown in blue<br>
ShpCircle.FillColor = QBColor(6) ‘ Will be shown in yellow
Control Arrays
Array – A group of data items that are referred
to by the same name.
Control Array – A group of controls sharing the same name and event
procedures
Index – A variable used to refer to each element in the control
array.
Control Arrays can be used with the following controls:
- Text Boxes
- Option Buttons
- Check Boxes
- Labels
- Command Buttons
Control Arrays are most commonly used with text boxes and option buttons.
CREATING A CONTROL ARRAY:
drop a control o the form and assign it a name
drop a second control on the form and assign it the SAME name
You will be given a message saying that you already have a control named
‘whatever’ and asks you if you want to create a control array
Press “Yes” and this will create your control array.
Now, for each subsequent item added, give it the same name also.
Once you create the control array, each item within the array will have
an index. The first will be an index of zero, 2nd of 1, 3rd of 2 and so
forth…
Example Control Array using a Select Case:
This example is if you had 6 option buttons with names
of colors and a Rounded Square shape that will fill the color of the selected
option button.
Private Sub optColors_Click(Index As Integer)<br>
Select Case Index<br>
Case 0: shpRoundSquare.FillColor = vbBlack<br>
Case 1: shpRoundSquare.FillColor = vbBlue<br>
Case 2: shpRoundSquare.FillColor = vbYellow<br>
Case 3: shpRoundSquare.FillColor = vbGreen<br>
Case 4: shpRoundSquare.FillColor = vbRed<br>
Case 5: shpRoundSquare.FillColor = vbMagenta<br>
End Select<br>
End Sub
SUM AND AVERAGE OF TEST SCORES USING CONTROL ARRAYS:
Here is another example of a control array. This will be if you wanted to figure the sum and average of test scores.
'Calculating Sum and Average<br>
Private Sub cmdCalculate_Click()<br>
For X = 0 to 9 <br>
Sum = Sum + val(txtTest(X))<br>
Next X<br>
Average = Sum / 10<br>
End Sub
'Clearing text boxes and totals<br>
Private Sub cmdClear_Click()<br>
For Z = 0 to 9<br>
TxtTest(Z) = ""<br>
Next Z<br>
LblSum = ""<br>
LblAvg = ""<br>
Sum = 0<br>
Average = 0<br>
End Sub<br>
Scroll Bars and RGB Function
Scroll Bar – A control that allows you to see hidden information on the screen. This information can be text, icons or controls.
In VB a scroll bar is used to represent a range of values.
Scroll bars are also used to control sound level, color, size and other values that can be changed in small amounts or large increments.
Scroll Box – The little square, which appears inside the scroll bar. Pressing down on the scroll box changes the value property of the scroll bar. Another name for the scroll box is the thumb.
PROPERTIES OF THE SCROLL BAR:
- Min – The smallest value the scroll bar can take
on - Max – The largest value the scroll bar can take on
- Small Change – The distance to move when the user clicks on the
scroll arrows - Large Change – The distance to move when the user clicks on the
gray area of the scroll bar - Value – Indicates the current position of the scroll bar and its
corresponding value within the scroll bar.
TYPES OF SCROLL BARS:
- Vertical Scroll Bar – Begins with the prefix “vsb”
- Horizontal Scroll Bar – Begins with a prefix “hsb”
EVENTS OF THE SCROLL BAR:
Change Event – Occurs when the user clicks on the
gray area of the scroll bar.
Scroll Event – Occurs when the user drags
the scroll box.
As soon as the user releases the mouse botton, the scroll event ceases and a change event occurs. When you write code for the scroll bar, you will want to write code for both Change even and the Scroll event.
SAMPLE PROGRAM USING HORIZONTAL SCROLL BAR:
Private Sub cmdExit_Click()<br>
End<br>
End Sub
Private Sub Form_Load()<br>
Hscroll.Top = (Screen.Height - Hscroll.Height)/2<br>
Hscroll.Left = (Screen.Width - Hscroll.Width)/2<br>
End Sub
Private Sub hsbScroll_Change()<br>
LblValue = hsbScroll.Value<br>
End Sub
Private Sub hsbScroll_Scroll()<br>
LblValue = hsbScroll.Value<br>
End Sub
SAMPLE PROGRAM USING VERTICAL SCROLL BAR:
Private Sub cmdExit_Click()<br>
End<br>
End Sub
<font color="#000000">Private Sub Form_Load()<br>
Vscroll.Top = (Screen.Height - Vscroll.Height)/2<br>
Vscroll.Left = (Screen.Width - Vscroll.Width)/2<br>
End Sub</font>
Private Sub vsbScroll_Change()<br>
LblValue = vsbScroll.Value<br>
End Sub
Private Sub vsbScroll_Scroll()<br>
LblValue = vsbScroll.Value<br>
End Sub
RGB FUNCTION
The RGB function specifies the quantities of red, green
and blue for a large variety of colors. The value for each color ranges
from 0 to 255 with 0 being the least intense and 255 being the most intense.
The color arguments are in the same order as their letters in the function
name, red first, then green and then finally blue. You can use the RGB
function to assign the color to a property or specify the color in a graphics
method.
Chosen_Color = RGB(RedValue, GreenValue,BlueValue)
Examples:
RGB(0,0,0) 'would be <b>BLACK</b><br>
RGB(255,255,255) 'would be <b><font color="#FFFFFF">BRIGHT WHITE</font></b><br>
RGB(255,0,0) 'would be <b><font color="#FF0000">RED</font></b><br>
RGB(0,255,0) 'would be <b><font color="#009900">GREEN</font></b><br>
RGB(0,0,255) 'would be <font color="#0033CC"><b>BLUE</b></font>
Multiple Forms
A VB project can consist of several forms. Each form has its own window, form load section, general declarations section and code window. All of the forms in a project are tied together under the project
name. When you run the program, you can switch back and forth between different forms.
StartUp Form – The first form a project displays
when the project is loaded.
Load – Loads a form into the computers memory (does not display on screen.)
- Load <form_name>
Unload – Unloads the form from the computers memory.
Also, if you’re running an execss amount of forms, you should unload
them to save up on memory.
- Unload <form_name>
Show – Display the loaded form on the screen.
- .Show <form_name>
Hide – Makes the form disappear. The form will
still be loaded into memory. It just will not be displayed on the screen.
- <form_name> .Hide
ME KEYWORD:
You can refer to the current form by using the special
keyword ME. Me acts like a variable and refers to the form that is currently
active. You can use Me in place of the form name when coding statements
and methods.
Examples:
Unload Me 'Unloads the current form that is executing
code<br>
Me.Hide 'Hides the form currently executing code<br>
Me.Show 'Shows the form currently executing code
Alright! Whew…for me, I believe that is a pretty good start on VB 6.0.
This tutorial does not cover many things but you can learn a lot just
by playing around with the program. Im sure I left a lot of things out
that I should have put in here and entered things I could have left out
but this is my first tutorial, so take it easy! Anyways, hope you enjoy
and are ready to code in Visual Basic!!!
–bs0d