Programming Using Visual Basic 6
Programming Using Visual Basic 6
Programming Using Visual Basic 6
Prepared by:
Ritchie P. Maribojoc, MSIT-CpE
Instructor
Why VB? Rationale…
2
The VB IDE View Code View Object
Menu bar Project
Tool bar Explorer
Window
Tool box
Properties
Project Window
Window
Immediate
Window
3
View Menu
4
Objects
Every VB app has at least one
object – the form.
7
The Inevitable Hello World Program
1. Open VB and
choose a New,
Standard Exe
program.
8
Hello World
2. Name the form
frmHelloWorld
3. Type in the
Caption as
shown. Note
it change in
the title bar.
9
Hello World
11
Font Property
9. Choose the
Font
property
and make
your font
larger and
of a
different
type.
12
Alignment Property
13
Command Button
11. Add a
command
button by
double
clicking that
object in the
toolbox.
Move it as
shown.
12. Name the
button
cmdDisplay
and change
the caption to
Display.
14
Done Button
13. Add a button
called cmdDone
and change the
caption to Done.
Note: If you choose
to Copy and
Paste a control,
you will get a
message box re:
Control Array.
Answer “NO” to
this.
15
Time to Code
We will begin coding
with the
cmdDone_Click
event procedure.
14. Double click the
Done button on the
object. This will
open up the code
editor window as
shown. Type in
Unload Me.
16
Unload Me
Adding the code Unload Me to the
cmdDone_Click event tells the
computer that when the control named
cmdDone is clicked, the form (me)
will unload.
To run your program, choose Run from the
menu, press F5, or click the Run button
on the toolbar.
Clicking the Done button should unload
your form.
17
Display Button
The code for the Display button will make the Caption in the
label lblMessage change to “Hello, World”.
15. Double click the Display button and type in the following
code:
lblMessage.Caption=“Hello, World”
Run your program and click the
Done button.
18
Details – Default Buttons
It would be good if the user could simply hit the <Enter> key to
have the message change.
16. Choose the Display button, find the Default
20
Moving Your Program and Creating an exe.
22
Colors on Buttons
You change the color of a button’s background,
but first you must set it’s Style property to
Graphical.
20. Choose the Display button, then change the
Backcolor and the Style property.
Note that there is no Forecolor…the font stays
black.
23
Graphics
We can also add graphics to some objects.
25
Comments
Adding comments in VB is done by prefixing your statement
with an apostrophe. For example:
‘this is a comment and will be ignored by the computer
Comments turn green when typed correctly.
24. At the top of your program, add comments with your
name, date, and project info as such:
‘RICHARD GOMEZ
‘Hello World project
‘JANUARY 24, 2014
Run your program. We are done!
26
Break Time!
27
Pizza Project
28
1. Create a new project by first
removing the current project.
Save as Pizza.
2. Add a label and format it as
you desire.
3. Add an image control and
name it imgPizza. The
image seen here is found at
D:\\images.
29
4. Add and name labels Choose the Text property and
and textboxes to delete it’s contents to remove
correspond to the figure Text1 from the text boxes.
at the right. Don’t
worry about lining
them up perfectly yet.
txtName
lblName
txtPhone
lblPhone
30
Aligning
You can line up objects on your form evenly by selecting
them (holding down the shift key allows multiple
selections) and then choosing Format, Align, etc. Notice
the other options under the Format menu.
5. Line up your labels and text boxes.
6. Choose both labels and text boxes at the same time, then
select Font and make them all 10 or 12 point.
31
Frames
Frames are used as containers for other controls. Usually
groups of option buttons are placed in frames.
32
Option Buttons in Frame
These are used when only one button of a group should be
selected. For example, a pizza size choice cannot be both
large and medium at the same time.
35
Checkboxes
Checkboxes allow the user to select (or deselect) an option.
Any number of checkboxes in a group may be selected. If
selected, it’s value is vbChecked, otherwise it is
vbUnchecked.
37
Time to Code!
The specs for this program state that the order can
be cancelled at any time. After order
placement, a message box will appear asking
the user to verify the order as indicated. If it is
verified another message box will indicate this.
38
Enabling and Disabling
39
Enabling Controls
It would be appropriate for these
checkboxes to be enabled after
choosing a pizza size.
17. Double click optSmall, and add this
code to the procedure.
chkPepperoni.enabled=true
Run the program. Click on Small and
Pepperoni should become enabled.
18. Enable each of the checkboxes in the
same manner.
40
Copy and Pasting Code
41
The Address Box
We don’t need the address
box if the order is for
Pickup, so it should not
be visible until the
Delivery button is
selected.
20. Choose lblAddress and
txtAddress and make
Visible = false in the
properties window.
42
Delivery Option Button
43
Pickup Option Button
Just as Delivery should make the Address info
visible, Pickup should make them invisible.
22. Add the following to the optPickup_click
procedure:
txtAddress.Visible = false
lblAddress.Visible = False
44
Cancel Button
If the user clicks the
Cancel button, all the
info currently entered
should disappear and
the form reset to the
initial screen.
23. Get to the
'clear the text boxes
cmdCancel_click
procedure and enter txtName.Text = ""
the following lines of
code: txtPhone.Text = ""
txtAddress.Text = ""
45
Canceling, continued
'clear the size options
optSmall.Value = False
optMedium.Value = False 'clear the checkboxes
chkPepperoni.Value = vbUnchecked
optLarge.Value = False
chkSausage.Value = vbUnchecked
chkMushrooms.Value = vbUnchecked
'set the pickup option chkGreenPeppers.Value = vbUnchecked
optPickup.Value = True chkExtraCheese.Value = vbUnchecked
chkOnions.Value = vbUnchecked
46
Canceling, continued
Last of all, disable the checkboxes again and set the focus to
txtName.
‘set focus
txtName.SetFocus
47
Break Time!
48
Global Variables
We are going to
use some Global
variables for
this program.
24. Add the lines
shown to your
program. These
variables can be
used by all the
procedures.
49
Constants
Every time the user selects or de-selects a topping, the topping price
must change. In this case, toppings are 75 cents each.
25. Constants should be declared before variables, and these are global
as well, so add them BEFORE the 2 global variables you just added.
50
Topping Price
We need to ADD to the curToppings every time a new
topping is selected, and SUBTRACT every time one
is de-selected.
26. In each chk procedure, add code similar to the
following, changing the Pepperoni to the appropriate
topping.
If chkPepperoni.value=vbChecked then
curToppings=curToppings + curToppingPrice
Else
curToppings=curToppings –curToppingPrice
End if
51
The Immediate Window
For testing purposes, you can View the Immediate
window and see the results of the debug.print
item statement that can be included in the code.
Add this line to each chk procedure.
Debug.print “Toppings =“
;curToppings
When you run your program, select and de-select
different checkboxes and watch the results in the
immediate window.
52
Debug.Print
statements
Results of
Debug.print
53
Size Price
54
Total Price
We need to calculate the total due as an addition
of curSize and curToppings.
27. Declare curTotal as a global variable of type
currency.
Private curTotal as currency
in the General section.
55
Calculating the Total
To calculate curTotal, we need to add a line to every
procedure that affects the price.
curTotal=curToppings + curSize
28. Add this line to all the options for size and the
checkboxes. (Thank goodness for copy and paste!)
If you change your Debug.Print statement as shown, you
can watch the totals as you run your program. Use
Edit, Replace to do this.Also, copy and paste it to
your options after the lines that calculate these totals.
29. Debug.Print "Toppings =";
curToppings; "Total is"; curTotal
56
Verifying the Order
Now that we have the totals working properly, we
need to manipulate some strings.
We want a message box similar to the figure to
appear when the Order button is clicked.
30. Declare a global variable to contain a string
representing the size of the Pizza.
Private strSize as string
57
strSize
31. In each of the procedures for the size
options, add a line to assign a string to string
size that corresponds with the size.
For example, in optSmall add:
strSize=“Small”
In optMedium, add strSize=“Medium” &
in optLarge add strSize=“Large”.
58
Check for Required Input
32.Add the following Dim blnValidData As Boolean
code to verify that
no required 'error checking
options or blnValidData = False
textboxes are left
blank. We do not If txtName.Text = "" Then
have time to
validate the input MsgBox "Invalid name"
today.
txtName.SetFocus
ElseIf txtPhone.Text = "" Then
MsgBox "Invalid phone"
txtPhone.SetFocus
59
‘to be continued
Run your project and
click the order ElseIf strSize = "" Then
button with some MsgBox "Invalid size"
text boxes left
blank. optSmall.SetFocus
ElseIf optDelivery.Value = True And
txtAddress = "" Then
MsgBox "Invalid address"
txtAddress.SetFocus
Else
blnValidData=True
60
End If
Create a Toppings List
Once we have validated entry in each required control,
we can create a toppings list. Note the indenting.
33.
vbCrLf – carriage return,
'list toppings in a string line feed
If blnValidData = True Then
If chkPepperoni.Value = vbChecked Then
strToppings = strToppings & vbCrLf &
"Pepperoni"
End If
&
If chkSausage.Value = vbChecked Then
strToppings = strToppings & vbCrLf & concatenate
61
"Sausage"
Toppings, continued
Copy and paste the if …then statement for Pepperoni 5 times
to create appropriate if statements for all of the toppings,
as shown for Sausage.
A message box can be a quick test to see if this works:
62
Delivery Method
The following code can be used to determine the
appropriate string for the method of delivery:
34. Declare a variable strDeliveryMethod as string in
the Order procedure. Then add the following to the
bottom of the procedure.
'check for delivery or pickup
If optDelivery.Value = True Then
strDeliveryMethod =
"Delivery"
Else
strDeliveryMethod = "Pickup"
End If
63
Message Boxes Revisited
There are different parameters you
can use with Message Boxes.
See the Help for a complete list.
We are going to ask the user to
click Yes or No to confirm the
order. We want their response to
be stored so we can act upon it.
If it is yes, the form should print
and clear. If no, the message box
should simply disappear and
allow the user to make the
required changes.
64
Message Box String
The following code will output a message box with the appropriate
strings and the Yes/No buttons.
35. First, declare a variable in the declaration section of the procedure.
65
Msgbox()
intOrderCorrect = MsgBox("Order for " & txtName &
vbCrLf _
& strSize & "Pizza for " & strDeliveryMethod &
" with" _ & vbCrLf & strToppings & vbCrLf &
vbCrLf & _
"Total = " & Format(curTotal, "currency") & _
vbCrLf & vbCrLf & _
"Is this order correct?", vbYesNo, "Verify
Order")
_
at the end of a line means that _
the code is continued _
on the next line even though _ 66
vbYes, vbNo
If the order is correct, print the form and clear it
(the same as Canceling).
If intOrderCorrect = vbYes Then
Me.PrintForm
Call cmdCancel_Click
End if
If the order is not correct, do nothing to the
program.
67
Program Complete!
68