You are on page 1of 37

Introduction to VB

Visual Basic is an event-driven language. So, when you talk about events,
we're talking about things that happen in the program which cause little
events to occur (similar idea to IRQ stuff you learned hopefully in 455). An
example of this could be clicking a button causing a button_click event to be
generated. You write code to react to these events and guide a user through
your program.
You design your form completely visually, using a set of widget tools and
drawing on the form directly just like you would in a paint program or
something like this. This stuff is so easy, you'll love it ... or maybe not ... but
it's quick and relatively pain free.
Okay, these examples were developed by James Tam, and I've just
reproduced them here. His website has all his full details on what exactly
these things entail, but I'll get into them a little bit myself. If it seems that
there's something missing here, be sure to check out over there for more
info.
Okay, the first thing you need to do with visual basic is basically just start it
up. No problem. Go:
Start --- Programs --- Microsoft Visual Basic --- You get the picture .... :)
When you load it up for the first time, Microsoft Office might churn away for a
couple of minutes. This is an issue with Office 2000 and you don't need to
worry about it too too much. It will only happen the once. In any case, when
VB is finally loaded up, and you pick Standard Exe from the new project
dialog, here's what you'll be confronted with:

Click image for a complete description...


This is your main programming environment. You do all your form design and
coding from this window. Now, probably the best way to get right into this
thing is to sit down and just hack out a quick program. Like I say, these are
ones that James made, and they're perfect for our purposes so kudos to
him. :)
Okay, great, now just exit VB without saving whatever you've done.

back to the top!!


Open and Run the First Example Program
I figure the best way to get introduced to VB is to open a program and run it
and play around with it, so that's going to be the order on this page. Open it,
run it, then we'll design it from scratch. The first program is James' first
example. Here's a link to download a zip file containing the example:
Click here to
download
Okay, the steps to follow:
Just save the file to your desktop.
Double click the file to open it with winzip.
Click "Extract" and extract the file to your desktop
This is what a VB
(note: you need to extract both files).
On your desktop, you should now have a folder called Project File Icon looks
like. FYI. :)
"example01"
Go in there and double-click "firstproject.vbp" (.vbp stands for "Visual Basic
Project")
Now, you should get VB loaded up with that project, no problem!
With that going, you can push the play button (center of the top tool bar) and
see what it looks like. There are a couple of things you can do with it:
If you push the button, you'll see the text there change
if you move your mouse around, it'll track your mouse movements by
displaying the coordinates
you can change the background colour by clicking the checkbox

here's the first sample program window


Great, you've seen that VB works. Now what? Well, at this point there are a
couple of things you can do. One is poking around with this program, looking
at James' code, or you can close this up and design it from scratch (should
take you like 5 - 10 minutes!!). I suggest building it. :)

back to the top!!


Build the First Example from Scratch
Okay, this is going to be hella-easy. :) I'll insert little comments in this step by
step process where you can run the program and try it out as you go along.
Okay, on with the fun!!
Start Visual Basic and pick "Standard Exe" from the list of new projects. You'll
land in the screen we saw above.
Go to the properties page (on the right) and find the caption property for the
main form (Form1). Change that to My First Example Program or something
lame like that. :)
Add a Command Button to the form by clicking the
tool and then drawing
on the form.
Now, click once on the button you just drew to select it and go to the
properties page on the right-hand side of the screen. Find
the (name) property and change it to cmdPressMe.
Next, in the same properties page, find the caption property and change its
value to Press Me.
Now, double click the button. This will bring up the code-view window. Type
in the following code into the cmdPressMe_Click() subroutine shell that's
generated for you:
'Note: comments have an apostrophe (') at the beginning of the line
Private Sub cmdPressMe_Click()
cmdPressMe.Caption = "You pressed me!"
End Sub
At this point, you can run the program and press the button to see what
happens.
Okay, next on the list is to add two labels. Labels are added with the
tool.
By selecting each label in turn, change their (name) properties
to lblCoordsA and lblCoordsB, respectively.
Now, change the caption property of lblCoordsA to read Current mouse
coordinates: and just leave the other one the way it is.
At this point, just double click somewhere on the form, but not on any of the
controls or labels you have added. This should yield you the shell for
the Form_Load() subroutine. Now for a little lesson in events. :) With Form as
your active object, select the MouseMove event from the event list as
pictured below.

When you click it, you should get the shell for
the Form_MouseMove( ... ) subroutine. Here's the code you want for that
routine:
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As
Single, Y As Single)
lblCoordsB.Caption = "x = " & X & " y = " & Y
End Sub
Now when you run the program, you should get an active record of where
your mouse is when you move it around on the form.
Okay, good to go. One last thing to add to this program. Using the
tool,
draw a checkbox on the form.
Change the (name) property of the checkbox to chkBGColour.
Then, change the caption property of the checkbox to read Change
Background Colour.
Next, double click the checkbox to give yourself a shell for
the chkBGColour_Click() event handler. The code for that routine looks like
this:
Private Sub chkBGColour_Click()
' If CheckBox checked then set background of form to red.
If (chkBGColour.Value = Checked) Then
Form1.BackColor = RGB(255, 0, 0)
' If CheckBox is unchecked then set background of form to grey.
ElseIf (chkBGColour.Value = Unchecked) Then
Form1.BackColor = RGB(210, 210, 210)
End If
End Sub
And that should pretty much do it for the program. If you run it now, it should
do all the same stuff that the example you downloaded did.
back to the top!!
Open and Run the Second Example Program

The second example program is a little more complicated, but not that much.
It just shows you a bit about list boxes and throwing stuff back and forth.
Cool, without further adue, check out the download link:
Click here to
download
Okay, the steps to follow:
Just save the file to your desktop.
Double click the file to open it with winzip.
Click "Extract" and extract the file to your desktop
The project file for the
(note: you need to extract both files).
On your desktop, you should now have a folder called second example
program.
"example02"
Go in there and double-click "Example2.vbp" (.vbp stands for "Visual Basic
Project")
Now, you should get VB loaded up with that project, no problem!
With that going, you can push the play button (center of the top tool bar) and
see what it looks like. There are a couple of things you can do with it:
You can add whatever text is typed into the text box as an entry in the
listbox.
You can remove entries from the listbox by pressing the "remove" button.

second example main window


Hip fantastic, eh? :) Again, many thanks go out to James for making this
example. Now, let's just build this thing from scratch to make sure you know
what you're doing.
back to the top!!
Build the Second Example Program from Scratch
Okay, this is going to be hella-easy. :) Okay, on with the fun!!
Start Visual Basic and pick "Standard Exe" from the list of new projects. You'll
land in the screen we saw above.

You know how to change the caption property of the main form, but you don't
need to ...
Okay, I'm going to give this to you really quickly.
Add a button.
change its caption to &Add - note: the '&' will make the letter after it a
keyboard shortcut
change its (name) to cmdAdd
Add another button.
change this second button's caption to &Delete
change that button's (name) to cmdDelete
Add a label.
change the label's caption to Text to add or which ever saucy comment you
like. :)
Add a textbox using the
tool (just draw it on the form like the other
controls!)
change that textbox's (name) to txtAddText
Add a listbox using the
tool (again, just draw it on the form!)
change that listbox's (name) to lstTextList
And that should be it for the Form Design portion of this program. Now we
just have to fill in the code for each of these controls.
Double-click on the form ... but be careful to not double-click on any of your
controls! This should get you the Form_Load() routine. Note: this gets called
automatically every time the form loads up from scratch... Here's the only
code for that:
'if there's nothing in the listbox, disable the delete button...
Private Sub Form_Load()
If (lstTextList.ListCount = 0) Then
cmdDelete.Enabled = False
End If
End Sub
Now, go back to the form design window and double-click the Add button.
The code for cmdAdd_click() is as follows:
Private Sub cmdAdd_Click()
' Add the string that is currently in the textBox to the List Box.
lstTextList.AddItem txtAddText.Text
' delete button disabled? enable it. :)
If (cmdDelete.Enabled = False) Then
cmdDelete.Enabled = True
End If
End Sub
Once that's done, get the form design and double-click the Delete
button. cmdDelete_Click() looks like this:
' This method contains the code for the click event for the delete button.
Private Sub cmdDelete_Click()

' if the listbox isn't empty, remove an item ... disable delete button if
necessary...
If (Not (lstTextList.ListCount = 0)) Then
lstTextList.RemoveItem (lstTextList.ListCount - 1)
If (lstTextList.ListCount = 0) Then
cmdDelete.Enabled = False
End If
End If
End Sub
And we are done! If you run the program now, you should be able to add and
remove stuff from the listbox depending on what you type in the textbox.
Fun, eh? :)
back to the top!!
MSDN Visual Basic Documentation
The MSDN Library is available from a few different locations and contains
a ton of information about Visual Basic and other Microsoft Visual Studio
stuff. (I'm not pluggin' it, I'm just saying it's useful if you're using the
products. :) ) Anyways, here's some ways to get at it:
In the Start menu, it's under Microsoft Developer Network
In VB, just go to the help menu and hit Index
In a web browser, you can go to the MSDN online site (that has lots of
technical articles and other stuff). Their website
is http://msdn.microsoft.com/. This is the only resource that you can get at
from anywhere... ie, you can load the library browser from home unless you
have the disks. :)
Yeah. :) That's where you get it. If you load the program from VB or the start
menu, this is what your browser looks like:

the MSDN library window


Terrific, eh? :) Okay. You probably want to look up only stuff to do with Visual
Basic, especially if you're using the search engine. You can automatically

filter down what you're looking at by changing the active subset that MSDN's
looking at to just look at Visual Basic. It's as easy as picking the Visual Basic
subset from the dropdown list (see the picture, below)!! (damn that sounded
cheesey, I should be in marketing...) In any case, now stuff that's specific to
VB is black text in the index list and unrelated stuff is sorta greyed out.

choosing the active subset


That's about all I have to say about the MSDN library. It's a very complete
reference, but may take a little bit of getting used to. For a fun challenge, try
finding the VB function MsgBox and throwing one up in an example programs
... just by clicking a button or something.
back to the top!!
MSDN Sample Programs: The Location!!
The sample programs included in MSDN are also included online, but aren't
attached to the Library Browser. Unfortunately they are not installed on each
and every computer, but they exist on the server and there are a couple of
ways you can go about getting access to them.
Mounting the Directory as a Drive
Easy peasy. :) If you're on a 2000 box in the lab downstairs, double-click the
My Computer on the desktop.
Go to the Tools menu, and select Map Network Drive
In the path textbox, type in the path \\pc\user\pub\msdn\samples\vb98 and
then press Finish.

the map network drive dialog


When you're done with that, you should have a drive listed in your My
Computer that will get you directly to the sample programs, where you can
copy stuff out of to play with. There's tons of stuff in there!
Make a Desktop Shortcut to the Samples
Right-click on your desktop and select new - shortcut
In the location textbox of the dialog that pops up, type in the
path \\pc\user\pub\msdn\samples\vb98 and then hit next.
When you hit finish, that shortcut on your desktop should fly you right to the
Samples folder.

create a new shortcut dialog

Download and Run Example Program 3


This week, we do a slightly more complicated example and make use of the
MSFlexGrid Control to interface with a database built in MS Access. It's a
really cheap CD Collection database so you can have a nice cheap computer
list of all the CDs you own. It's braindead. :) This is so easy and the code is so
short, that's my only note for now. :) Let's just jump right in on this thing by
downloading it and running it:
Click here to
download
Okay, the steps to follow:
Just save the file to your desktop.
Double click the file to open it with winzip.
Click "Extract" and extract the file to your desktop
The project file for the
(note: you need to extract both files).
On your desktop, you should now have a folder called cheap database
program
"flexample"
Go in there and double-click "Projcet1.vbp" (.vbp stands for "Visual Basic
Project")
Now, you should get VB loaded up with that project, no problem!
With that going, you can push the play button (center of the top tool bar) and
see what it looks like. There are a couple of things you can do with it:
You can add CDs to the Database by entering some info in the textboxes and
pushing the "Add This Info" button
You can select a row from the grid and hit the "Remove Selected" button to
remove it permanently from the database

The Cheap CD Collector program window


Pretty amazing, eh? :)
back to top!!
Build Example Program 3 From Scratch
Okay, already you can tell that this one is a little more complicated to
build ... but it's still surprisingly simple to get a database application going.
The only tricky part of it is watching database versions.
This is just a very simple, brain-dead database and app, so it's not meant to
be sophisticated or correct in terms of database design in any way!! The first
thing you need to do is just make yourself up a database table in Access and
save it to an mdb file. Sooooooo simple:
The Database Design
Open up MS Access (Start - Programs - Microsoft Access)
Pick "Start a blank database" from the wizard that pops up
Pick a spot to save the mdb file and a name for it (mine was
"CDCollectionA.mdb")
You'll get to the following window, where you double click on "Create a table
in design view:"

the database design main window


When you double click that "create table in design view" thingie, you get to
this window:

The table design view window


You want to follow the following steps to get the table I was working with:
Make a field called ArtistName whose type is Text
Make a field called AlbumTitle whose type is Text
Make a field called Tracks whose type is Number (just a long integer is cool
enough)

Select the rows in the design view (as pictured above) that
have ArtistName and AlbumTitle
Right-click on that selection, and pick Primary Key from the menu you get.
This will make both fields into primary keys. The idea is that they can be
primary because you'll never have identical artist names and album titles
(otherwise what's the point?!).
Once you've got your table built, just close that window. You'll be
automatically prompted to save changes to the table design and to give the
table a name. I picked CDs, how original. :)
Once that's all done, you can either add a couple entries to the database by
double clicking the CDs table from the database design main window and
inputting them manually or just move on to:
Export the database to Access '97 (this is the annoying part of the whole
thing) Here's what you do:
Go to the Tools menu
Select Database Utilities
Select Convert Database
Select To Prior Access Database Version
You'll get a save file dialog that will let you enter a name for your database. (I
used "CDCollection.mdb") Just save it in the same folder as your Access 2000
version of the file. Whatever you call it, make sure you keep track of which
database file is which version!!

Export your database to a prior Access Database Version


The Software Design
Okay, now you've got the database file, and remember where you saved that
mdb file at the start of the process. That's where you'll save your vb project
too, just to keep things simple. You'll probably eventually want your program
and data living in the same folder for simplicity's sake, so it makes sense to
just start out like that. Okay, let's build this app:
Start up VB

Pick Standard EXE from the new project list


Add the MSFlexGrid control to your project:
Go to the Project menu, pick Components.
Scroll down the list of components until you find "Microsoft FlexGrid Control
6.0 (sp3)". Select that checkbox and hit the OK button to add the control to
your project.

Add a FlexGrid to your form by picking the


main form.
Add a data source to the form using the
Change its visibility property to False.

tool and drawing it on your


tool and drawing on the form.

Add two frames to the form using the


tool and drawing them on the form.
Change the caption of one to Add new entry and the caption of the other
to Remove Entry
Draw the following controls in the Add new entry frame (yes, actually in the
frame):
A text box with the (name) txtArtistName
A label above that text box with the caption Artist Name
A text box with the (name) txtAlbumTitle
A label above that text box with the caption Album Title
A text box with the (name) txtTrackCount
A label above that text box with the caption Number of Tracks
A command button with the (name) cmdAddEntry and the caption Add this
info

Now, to the Remove Entry frame, add the following controls:


A command button with the (name) cmdRemoveEntry and
the caption Remove Selected
A label with the caption Select the entry you want to remove and click the
button:
Now, the most complicated part is formatting the FlexGrid (which is
called MSFlexGrid1) to do what you want. It's fairly customizable, but here's
all I did for this example program:
the AllowUserResizing property was set to 1
the Cols property was set to 3
the DataSource property was set to Data1 (** this is required **) this hooks
the data source up to the FlexGrid.
the FixedCols property was set to 0 while the FixedRows property was set to
1. (this is recommended)
the FocusRect property was set to 0.
the HighLight property was set to 1.
the ScrollTrack property was set to True.
the SelectionMode property was set to 1 (selection by row only).
the WordWrap property was set to True.
Okay, next the code. In the form design window, double click the form, which
should bring up the code window with a blank Form_Load() subroutine.
Here's the code for it:
Private Sub Form_Load()
'the format string just lets you define a format for how
'your flexgrid will appear
MSFlexGrid1.FormatString = "Artist Name
|" & _
"Album Name
| Tracks"
'make sure the search path to the db is always in the right spot
Data1.DatabaseName = App.Path & "\CDCollection.mdb"
'set up the recordsource for the datasource and flexgrid control
'in this case, it's just a raw SQL query, simple simple.
Data1.RecordSource = "select * from CDs order by ArtistName"
End Sub
Now, go back to the form design window and double click the Add this
info button. You should now have a blank cmdAddEntry_Click() subroutine.
Here's what to fill in there:
Private Sub cmdAddEntry_Click()
'add a new entry to our table.
With Data1.Recordset
.AddNew
!ArtistName = txtArtistName
!AlbumTitle = txtAlbumTitle
!Tracks = txtTrackCount
.Update

End With
Data1.Refresh
'clear the text fields once the new record is added
txtArtistName = ""
txtAlbumTitle = ""
txtTrackCount = ""
End Sub
Last thing you need is the remove code. In the form design window, doubleclick the Remove Selected button. You should get a shell for
the cmdRemoveEntry_Click() subroutine. This is the code:
Private Sub cmdRemoveEntry_Click()
'delete an entry from the database
With Data1.Recordset
.Move (MSFlexGrid1.Row - 1) ' we minus one because row zero is the
header row
.Delete
End With
Data1.Refresh
'set the focus back to the first add field
txtArtistName.SetFocus
End Sub
And we are done! It's actually pretty simple to do this stuff, no problem!!
Before you run this thing, you will need to save the project to the same folder
that you saved your database file from the above section to.
back to the top!!
Download and Run Example Program 4
Example programs 4 and 5 were both written by Saul and have the basic
goal of teaching some more about event handling in VB as well as teaching a
little bit about how to go about using a canvas-style widget. Without further
adue, let's check out the first simple example:
Click here to
download
Okay, the steps to follow:
Just save the file to your desktop.
Double click the file to open it with winzip.
Click "Extract" and extract the file to your desktop
The project file for the
(note: you need to extract both files).
On your desktop, you should now have a folder called simple sketchpad
program
"Sketchpad1"

Go in there and double-click "Sketch1.vbp" (.vbp stands for "Visual Basic


Project")
Now, you should get VB loaded up with that project, no problem!
With that going, you can push the play button (center of the top tool bar) and
see what it looks like. Theres only one thing you can do with this one!!:
Click and hold the mouse on the canvas and roll it around to draw a cute blue
line

the sketchpad form in action (yes I'm rad)


back to the top!!
Build Example Program 4 from Scratch
Okay, let's actually get to work building this thing. This one is actually quite
simple to build and shouldn't take too long at all!! Check it out:
Start up VB with a Standard EXE project (this should be familiar terminology
to you by now).
Add a picturebox to the main form using the
tool and drawing on the
form. Just make it mostly the same size as the entire form. :)
Change the picturebox's (name) property to read picCanvas.
Now double-click on the form (not on the picturebox) to get access to a shell
for the Form_Load() subroutine. The code for that looks like:
Private Sub Form_Load()
'Redraws the image when the window is covered/uncovered
picCanvas.AutoRedraw = True
'The canvas look and drawing behaviour
picCanvas.DrawWidth = 2 'Lines are 2 units thick
picCanvas.ForeColor = vbBlue 'Lines are blue
picCanvas.BackColor = vbWhite 'Background canvas is white
End Sub
If you go back to the form-design window and double click on the picturebox
now, you'll get a shell for cmdCanvas_Click(). That's not the one you want.

From the dropdown list on the top of the code window, pick
the MouseDown event. Here's the code to fill that one in:
'Set the first point and start the line
Private Sub picCanvas_MouseDown(Button As Integer, Shift As Integer, X As
Single, Y As Single)
If Button = 1 Then
picCanvas.Line (X, Y)-(X, Y)
End If
End Sub
Once that's filled in, from the same event drop-down list at the top of the
code window, pick the MouseMove event. The code for that bad boy is right
here for the taking:
'Continue the line to the next point as we move the mouse
Private Sub picCanvas_MouseMove(Button As Integer, Shift As Integer, X As
Single, Y As Single)
If Button = 1 Then
picCanvas.Line -(X, Y)
End If
End Sub
That should be it! This is pretty simple, all it does is listen for a button click
with the left mouse button on the picturebox. If it gets a mousedown
followed by a drag, it draws a blue line (as was set up in the form_load
subroutine). Simple use of events makes a fun little app!!
back to the top!!
Download and Run Example Program 5
Example program 5 (also written by Saul) is an extention of the idea
presented by Example program 4. It has the same basic concept with a ton
of more features! I won't go through how to build it here, but leave it to you
to download this sucker and play around with it, because you can do some
pretty neat things pretty easily.
Fun challenge: try to implement a feature that would let you save whatever
you draw in the canvas to a bitmap or jpg file!
Click here to
download
Okay, the steps to follow:
Just save the file to your desktop.
Double click the file to open it with winzip.
Click "Extract" and extract the file to your desktop
The project file for the
(note: you need to extract both files).
On your desktop, you should now have a folder called extended sketchpad
program
"Sketchpad2"

Go in there and double-click "Sketch2.vbp" (.vbp stands for "Visual Basic


Project")
Now, you should get VB loaded up with that project, no problem!
With that going, you can push the play button (center of the top tool bar) and
see what it looks like. There's tons of stuff you can do with this one:
You can draw a line on the canvas
you can change the colour of the line you draw on the canvas
you can change the thickness of the line you draw on the canvas
you can clear your canvas and start from scratch (although witha picture like
this, why would you clear it??? :))

the hip sketchpad main form ... I'm still rad!!


Suggestion: check out the code for this bad boy and play around with
modifying it. There's a ton here and so there's tons to go from!!!

LESSON 4 - How to use the VB standard controls


Monday, March 07, 2016
For this lesson we will need a new Project, call it Lesson4.vbp, which will only
be used to create and try out various controls.
To refresh your memory, since the previous two lessons have been rather
theoretical, you select the New tab, and Standard EXE for the type. As soon
as The Form opens, you Save the new Project, give the Form a name, let's
say it's Lesson4.frm and then you give the Project a name: Lesson4.vbp.
Note that you do not have to specify the extensions, .frm and .vbp, because
they will be assigned automatically.
The Form
We covered it too briefly in Lesson 01 so we'll go over it again.
The Form is the first object you see when you Open the application. It's the
window into which all the controls will appear, where you will input data and
see results.

There's not too much you can do with the form at this time. Basically, you
adjust the BackColor and the StartUpPosition(where it will open on the screen
when you Run it) and then you start putting controls on it.

The Label
This is probably the first control you will master. It is used to display static
text, titles and screen output from operations. The important properties to
remember:
Caption - the text that is displayed in the label
BackColor and ForeColor - colors of the background and the text
BackStyle - Opaque or Transparent - whether the background is visible or not
Font - font and size of text
Alignment - text centered, left or right
Multiline- True or False - if True, you can have several lines of text, delimited
by <CR> in the label - by default, it is set to False

Frame & PictureBox


When you want to group several controls together - name and address, for
example - you use a Frame. The frame backcolor can be the same as the
form's and only the frame borders will be obvious, or it can be a different
color and stand out.
You create the frame before the controls. When you create controls in a
frame, they are tied to the frame and move with it. The frame caption is the
text that appears at the top of the frame - you use it to define the group.
The PictureBox is like a Label with a picture in it instead of text. The Picture
property determines the name of the file, .BMP or .GIF, that will be displayed.
It can be used for a company logo, etc.

Top

TextBox & CommandButton


The TextBox is like a Label but, it is used to input data into the program. The
data typed in is in the Text property of the control.
When the program is Run, only the controls that can be manipulated will be
activated. For example, if the form contains 3 Labels, 3 TextBoxes and 3
Buttons, when it is Run, the cursor will not stop at the labels.
When the user hits the Tab key, the cursor will go to the first TextBox or
Button - not necessarily the first one on the form but, the first one that was
created. That is called the Tab order and you have to specify it.
On the form there is only one control at any given time that has the cursor
on it - it is said to have Focus. If you type data, the control with Focus will
receive it. You change the Focus with Tab or by clicking on a different control.
Up until now we haven't bothered with the names of
controls (the Name property). Once we start to code,
however, it does become important. There are all
kinds of occasions in code where you have to call
upon a certain control. It can get very confusing when
your 12 buttons are called Command1...Command12.
What did Command7 do, again? Give each control a
name (except for titles, etc. that you never refer to)
so that you will be able to identify it easily. It is

recommended that you use a prefix when assigning a


name; cmd for a CommandButton, lbl for a Label, txt
for a TextBox. Thus, txtNumber where you input the
value can be distinguished from lblNumber where you
display the result.
The CommandButton is used to initiate actions, usually by clicking on it. The
Caption property determines the text to display on the face of the button.
The Default property, if set to true, means that the button will be activated
(same as Clicked) if the <Enter> key is hit anywhere in the form. If Cancel is
set to True, the button will be activated from anywhere in the form by the
<Esc> key.

Hopefully, you have now run this program several times, each time you
added a new control, in fact. Admittedly, nothing much happened except to
confirm that the controls were appearing in the right place on the form.
Here now is an example of the code we could write to perform simple tasks:
input name and city and display the information in a label when the Continue
button is clicked. The Exit button will end execution of the program and the
Cancel button (or the Esc key) will clear the fields.

A few explanations: the Form_Load event occurs when the form first opens.
This is where we initialize things - we want the TextBoxes and the result Label
to be empty when we start off so, we set them to a blank space.
The actual processing is done after the data have been entered and we hit
the Continue button. The processing logic is put in the
Continue_button_clicked event.
When you hit the <Esc> key or you click on the Cancel button, you want to
annul the entry you're doing and start over again. That's the same as
opening the form so, we just tell the program to execute the Form_Load
procedure which we already have.
The Exit button uses the pronoun Me to Unload. Me means the form currently
active without having to name it.
Top

Multiple forms
For the next series of examples we will use a new
Form. It is not necessary to create a new Project; any
Project can have several Forms in it.
With the Project open on the current Form, go to:
Menu --> Project --> Add form. Select New form in the
creation window and, voila! Next time you save the
Project, it will ask you to name this new Form. You can
name it Lesson4B.frm for example.
One more detail: when you Run the Project, you want
to tell it which Form to open.
Go to the Project Manager window, right click on the
Project name and select Project properties. In the
Project properties window, the ListBox on the right
says "Startup object". Select the Form you want to
open when you Run. You can change the Startup
object at any time to run the different forms that you
created.
Check boxes & Option buttons
These two controls are used when the user must choose from a list of
options. The difference between the two is that with Check boxes he can
select several at one time but, with Option buttons, he must select only one
among several.
The example below illustrates the use of Check boxes and Option buttons. To
capture the information entered by means of these controls, you must test
the property: Value. In a Check box, Value = 1 if box is checked and = 0 if
not. In an Option button, Value = True if selected and = False if not.

The code, although somewhat long, is not very complicated. Most of the
time, processing consists of checking the content of .Value. It is fairly
standard procedure, especially with Option buttons, to ensure that at least
one button has been selected and to display an error message if it has not.

Assignment 3
Create the Payroll form shown below. Number of hours must be entered as
well as the appropriate rate. Gross salary = rate * hours. Net salary = gross
salary - deductions.

Look at "Lesson 11 - Downloads" for the solution.

LESSON 2 - How to write code


Monday, March 07, 2016
The Code Editor
As we saw in the previous lesson, getting to the Code Editor is as simple as
hitting the proper button. You may have discovered that you can also call-up
the Editor by double-clicking on an object. It is also possible to select "View
code" with the right mouse button.

You will note that the Editor has all the functions of a text editor and then
some. The most commonly used functions will be Cut ... Copy ... Paste which
you can call from the Menu, from the Toolbar or from the right mouse button.
You also have access to the usual Find andReplace functions ....
Getting help
There is a lot of documentation available on VB. There is so much, in fact,
that it's easy to get lost in it. However, the on-line Help available from the
Menu should be used regularly. Very often just doing a search on a word in
particular will be sufficient to get you out of a jam. If you want to go into
more detail check out the Contents part of MSDN (Microsoft Developers'
Network) and surf through it.
Writing code
VB is not very particular about presentation - spaces, indents, lower case or
upper case, it doesn't make too much difference to the compiler. But it may
make a whole lot of difference to the programmer who has to maintain your
code in 2 years, after you've moved up to being CEO of the company.
Apply "Best Programming Practices"
When you work with RAD (Rapid Application Development)
tools like VB in a graphical interface environment, you
become more than just a programmer, a writer of code. You
are a developer. We will cover that in the next lesson.
But at the moment, you are still a Programmer. And unless
you are developing an application for your own personal use,
that nobody else will see, you have to think of the
environment, of the team you are working with.
"No man (or woman) is an island!"
Especially when it comes to programming. The code you
write may have to be checked by an Analyst. It will have to
go through testing. It may have to be modified by other team
members and it almost certainly will go through

modifications, maybe several times, in the months and years


ahead when you probably won't be around to defend
yourself. "The evil that men do lives after them...". You do not
write code for the VB compiler. You write it for other
developers and programmers. What you want others to say
behind your back is: "That Jane was blindingly efficient,
brilliant, a genius with comments ...". You do not want to be
remembered as "...the Picasso of code, master of the
abstract".
If you are just starting out with the language, why not pick up a few good
habits right now and it may make your life a lot easier down the road.
Use comments when appropriate but not so many as to overwhelm the code;
the apostrophe ' is the comment identifier; it can be at the beginning of a
line or after the code.
' This is a comment
' on 2 lines.
DIM intNumber AS Integer
'This is a comment
Use indents - code must be indented under control structures such as If ...
Then or Sub - it makes it so much easier to follow the logic.
FOR i = 1 TO 5
value(i) = 0
' Indent used in control structures
NEXT i
Use standard capitalization - keywords like If, Dim, Option, Private start with
a capital letter with the rest in lower case; variable names, control names,
etc. are usually mixed case: ClientName, StudentId, etc.
Write extra-long statements on 2 lines using the continuation character _
(space underscore); in VB each line is assumed to be an individual statement
unless there is a continuation at the end of the first line.
Data1.RecordSource = _
"Select * From Titles"

' One statement on 2 lines is OK

Naming conventions
These are the rules to follow when naming elements in VB - variables,
constants, controls, procedures, and so on:
A name must begin with a letter.
May be as much as 255 characters long (but don't forget that somedy has to
type the stuff!).
Must not contain a space or an embedded period or type-declaration
characters used to specify a data type ; these are ! # % $ & @

Must not be a reserved word (that is part of the code, like Option, for
example).
The dash, although legal, should be avoided because it may be confused
with the minus sign. Instead of Family-name use Family_name or
FamilyName.
Data types
Data type
Storage
Range
size
Byte

1 byte

0 to 255

Boolean

2 bytes

True or False

Integer

2 bytes

-32,768 to 32,767

Long (long
integer)

4 bytes

-2,147,483,648 to 2,147,483,647

Single
(singleprecision
floatingpoint)

4 bytes

Double
(doubleprecision
floatingpoint)

8 bytes

Currency
(scaled
integer)

-3.402823E38 to -1.401298E-45 for negative values;


1.401298E-45 to 3.402823E38 for positive values

-1.79769313486232E308 to -4.94065645841247E324 for negative values; 4.94065645841247E-324 to


1.79769313486232E308 for positive values

8 bytes

-922,337,203,685,477.5808 to
922,337,203,685,477.5807

Decimal

14 bytes +/-79,228,162,514,264,337,593,543,950,335 with no


decimal point; +/7.9228162514264337593543950335 with 28 places
to the right of the decimal; smallest non-zero number
is +/-0.0000000000000000000000000001

Date

8 bytes

January 1, 100 to December 31, 9999

Object

4 bytes

Any Object reference

String
(variablelength)

10 bytes
+ string 0 to approximately 2 billion
length

String (fixed- Length of


1 to approximately 65,400
length)
string
Variant (with
16 bytes Any numeric value up to the range of a Double
numbers)
Variant (with 22 bytes Same range as for variable-length String

characters) + string
length
User-defined Number
(using Type) required The range of each element is the same as the range
by
of its data type.
elements

In all probability, in 90% of your applications you will use at most six types:
String, Integer, Long, Single, Boolean and Date. The Variant type is often
used automatically when type is not important. A Variant-type field can
contain text or numbers, depending on the data that is actually entered. It is
flexible but it is not very efficient in terms of storage.
Top
Declaring variables
Declaring a variable means giving it a name, a data type and sometimes an
initial value. The declaration can be explicit or implicit.
An explicit declaration: variable is declared in the Declarations Section or at
the beginning of a Procedure. An explicit declaration looks like:
Dim MyNumber As Integer
Now the variable MyNumber exists and a 2-byte space has been reserved for
it.
An implicit declaration: the variable is declared "on the fly", its data type is
deduced from other variables. For example:
Dim Total1 As Integer
'Explicit declaration
Dim Total2 As Integer
'Explicit declaration
Total3 = Total1 + Total2
'Implicit declaration
Total3 is not formally declared but is implied, it is "arrived at" from the other
declarations.
It is never a good idea to have implicit declarations. It goes against the rules
for clarity, readability and ease of use of the code.
To make sure that this rule is followed, start the Declarations with the Option
Explicit clause. This tells the compiler to consider implicit declarations as
errors and forces the programmer to declare everything explicitly.
Other examples of declarations:
Dim MyName As String
Dim StudentDOB As Date
Dim Amount5, Amount6, Amount7
In the last example the type assigned to each variable will be: Variant. It is

the default type when none is specified.


There can be multiple explicit declarations in a statement:
Dim EmpName As String, SalaryMonth As Currency, SalaryYear As Currency
In this final example, what are the types assigned to the three variables:
Dim Amount1, Amount2, Amount3 As Single
All Single-precision floating point, you say. Wrong! Only Amount3 is Single.
Amount1 and Amount2 are considered Variant because VB specifies that
each variable in a statement must be explicitly declared. Thus Amount1 and
Amount2 take the default data type. This is different from what most other
languages do.
Constants
A constant is a value that does not change during the execution of a
procedure. The constant is defined with:
Const ValuePi = 3.1416
The Scope of variables
The term Scope refers to whether the variable is available outside the
procedure in which it appears. The scope is procedure-level ormodule-level.
A variable declared with Dim at the beginning of a procedure is only
available in that procedure. When the procedure ends, the variable
disappears. Consider the following example:
Option Explicit
Dim Total2 As Integer
Private Sub Command1_Click ()
Dim Total1 As Integer
Static Total3 As Integer
Total1 = Total1 + 1
Total2 = Total2 + 1
Total3 = Total3 + 1
End Sub
Private Sub Command2_Click ()
Dim Total1 As Integer
Total1 = Total1 + 1
Total2 = Total2 + 1
Total3 = Total3 + 1
End Sub
Every time Button1 is clicked, Total1 is declared as a new variable during the
execution of that clicked event. It is a procedure-level variable. It will always
stay at 1. The same for the Button2 event: Total1 is a new variable in that

procedure. When the procedure ends, Total1 disappears.


Total2 is declared in the Declarations section. It is a module-level variable,
meaning it is available to every control in this Form. When Button1 is clicked,
it increments by 1 and it retains that value. When Button2 is clicked, Total2 is
incremented from its previous value, even if it came from the Button1 event.
Total3 shows another way of retaining the value of a local variable. By
declaring it with Static instead of Dim, the variable acts like a module-level
variable, although it is declared in a procedure.
Another scope indicator that you will see when you study examples of code
is Private and Public. This determines whether a procedure is available only
in this Form (module) or if it is available to any module in the application. For
now, we will work only with Private procedures.
Top
Operators
Mathematical and Text operators
Operat
Definition
Example
Result
or
^

Exponent (power
4^2
of)

16

Multiply

5*4

20

Divide

20 / 4

Add

3+4

Subtract

7-3

Mod

Remainder of
division

20 Mod 6

Integer division

20 \ 6

&

String
concatenation

"Joan" & " " &


"Smith"

"Joan
Smith"

Note that the order of operators is determined by the usual rules in


programming. When a statement includes multiple operations the order of
operations is:
Parentheses ( ), ^, *, /, \, Mod, +, Logical operators
Operato
Definition
Example
Result
r
=

Equal to

9 = 11

>

Greater than 11 > 9

True

<

Less than

False

11 < 9

False

>=

Greater or
equal

<=

Less or equal 9 <= 15

True

<>

Not equal

9 <> 9

False

AND

Logical AND

(9 = 9) AND (7
False
= 6)

OR

Logical OR

(9 = 9) OR (7 =
True
6)

15 >= 15

True

Top

Control Structures
If...Then...Else
If condition1 Then
statements1
Else
statements2
End If
If condition1 is True, then statements1 block is executed; Else, condition1 is
not True, therefore statements2 block gets executed. The structure must be
terminated with the End If statement.
The Else clause is optional. In a simple comparison, statements1 get
executed or not.
If condition1 Then
statements1
End If
Select Case
Can be used as an alternative to the If...Then...Else structure, especially
when many comparisons are involved.
Select Case ShirtSize
Case 1
SizeName.Caption = "Small"
Case 2
SizeName.Caption = "Medium"
Case 3

SizeName.Caption = "Large"
Case 4
SizeName.Caption = "Extra Large"
Case Else
SizeName.Caption = "Unknown size"
End Select
Do...Loop
Used to execute a block of statements an unspecified number of times.
Do While condition
statements
Loop
First, the condition is tested; if condition is True, then the statements are
executed. When it gets to the Loop it goes back to the Do and tests condition
again. If condition is False on the first pass, the statements are never
executed.

For...Next
When the number of iterations of the loop is known, it is better to use the
For...Next rather than the Do...Loop.
For counter = start To end
statements
Next
1) The counter is set to the value of start.
2) Counter is checked to see if it is greater than end; if yes, control passes to
the statement after the Next; if not the statements are executed.
3)At Next, counter is incremented and goes back to step 2).
More will be covered on Control strucures as it becomes necessary in
upcoming lessons. Meanwhile,if you want to know more, consult the VB
Language Reference.

You might also like