Wyo VB - Ch. 6 Notes
Objective #1: Use general procedures in a project.
- Besides event procedures, you can place code in general procedures
(also known as general sub procedures). This is efficient because that code
can be reused without requiring the user to click the mouse or perform other
event.A specific task that you need to perform in the logic of your algorithm
over and over again should be placed into a general procedure.
- An example of a general procedure is:
Private Sub ChangeColor( )
' changes the background color of the form to red
frmMain.BackColor = vbRed
End Sub
- The first line of a general procedure is called its header. The header
for the example general procedure above is:
Private Sub ChangeColor( )
Notice that like an event procedure the first two words in the header are
Private Sub. Later we will learn that it is convenient to use Public instead
of Private for some general procedures. Also observe that the parentheses
are required. The name of the general procedure, ChangeColor in this case,
can be anything the programmer desires. However, you should use logical names
for general procedures that indicate their purpose. You should also use the
InterCap method of capitalizing each word in the name of the general procedure.
No prefix is required though for a general procedure's name.
- A general procedure executes just as an event procedure does except that
there is no event that is directly associated with it. For example, a user's
click of the mouse would not directly cause the ChangeColor general procedure
to execute. However, an event procedure (or another general procedure) can
call a general procedure using a call statement. The Click event procedure
below would call the general procedure ChangeColor so that, in effect, a click
of the mouse on the command button cmdMakeRed would indirectly make the form
red.
Private Sub cmdMakeRed_Click( )
Call ChangeColor
End Sub
- The call statement in the example above is the line of code
Call ChangeColor
Simply typing the VB command Call followed by the name of a general procedure
causes VB to execute the specified general procedure at that moment. Some
times the word Call is optional allowing you to use the call statement:
ChangeColor
I prefer that you do use the word Call to indicate call statements in Visual
Basic.
- You can pass a parameter to a general procedure to make it even more
flexible. Just like VB's textbox KeyPress event uses a parameter named KeyAscii,
you can create your own parameters to use in conjunction with your general
procedures. In the following example, strColor is a parameter.
Private Sub ChangeColor(strColor As String)
' changes the background color of the form
If (strColor = "red") Then
frmMain.BackColor = vbRed
ElseIf (strColor = "blue") Then
frmMain.BackColor = vbBlue
ElseIf (strColor = "green") Then
frmMain.BackColor = vbGreen
End If
End Sub
The following event procedure could be used to call the general procedure
ChangeColor:
Private Sub cmdClick_Click( )
Dim strInput As String
strInput = txtInput.Text
Call ChangeColor (strInput)
Beep
End Sub
If the user types "red" into the textbox txtInput, the call statement
passes the string literal "red" as a parameter to the general
procedure ChangeColor because strInput is typed in the parentheses of the
call statement. This process is called "passing a parameter" ( or
"passing an argument") because strInput is considered to be a parameter
in this situation. The parameter strInput is being passed from the event procedure
cmdClick_Click to the general procedure ChangeColor.
On the receiving end, the general procedure ChangeColor receives the parameter
because of the parameter name strColor that is used in the parentheses of
its header. Even though the parameter name strColor does not have the same
name as the parameter strInput. Since both of these parameters are declared
as Strings, no compile errors occur. The general procedure then changes the
background color of the form to red due to the use of the If/ElseIf statement
in the procedure ChangeColor.
After the general procedure ChangeColor is finished executing Visual Basic
returns to the event procedure cmdClick_Click to finish executing any statements
that are found there below the call statement. Since the Beep command is located
after the ChangeColor call statement, the program would then beep.
Objective #2: Use general functions in a project.
- General functions (or just called functions) are similar to general
procedures. However, in addition to parameters that may be passed to the function,
a function returns a computed value. The computed value is returned to the
procedure or function that called the function.
- An example of a function is
Private Function sngComputeTax(ByVal sngPrice As Single) As Single
Dim sngPriceWithTax As Single
sngPriceWithTax = sngPrice + sngPrice * 0.06
sngComputeTax = sngPriceWithTax
End Function
- Notice the use of the keyword Function instead of Sub in a function. Also
notice the safe use of the keyword ByVal in the parameter list (i.e. in the
parentheses). We will learn what ByVal really means later. Finally, notice
the last statement in the body of the function. The function's name itself
sngComputeTax is treated as if it were a variable and it is assigned the value
of sngPriceWithTax. This causes that value (say 34.52) to be returned to the
calling procedure or function. Finally, it is proper to type ....As Single
at the end of a function header if the function returns a Single value. If
the function returned an Integer value it would be appropriate to type ....As
Integer instead of ....As Single.
- An example of calling the function sngComputeTax is given in the following
event procedure.
Private Sub cmdCalculate_Click()
Dim sngPrice As Single
Dim sngFinalPrice As Single
sngPrice = Val(txtInput.Text)
sngFinalPrice = sngComputeTax(sngPrice)
lblOutput.Caption = "The price with tax is " &
sngFinalPrice
End Sub
The statement
sngFinalPrice = sngComputeTax(sngPrice)
can be considered the call statement where sngPrice is passed as a parameter
to the function sngComputeTax. However, the value that is returned by the
function is automatically assigned to the local variable sngFinalPrice. Then
it is simply a matter of displaying the variable sngFinalPrice in the label
lblOutput.
The kind of call statement that calls a function is slightly different from
a call statement that calls a general procedure. Really this call statement
that calls the function sngComputeTax can also be considered an assignment
statement because the returned value is assigned to a variable in the same
statement.
Here is another example of an event procedure that calls the function sngComputeTax.
Private Sub cmdCalculate_Click()
MsgBox sngComputeTax(Val(txtInput.Text))
End Sub
the programmer does not use any local variables in the cmdCalculate_Click
event procedure and he is using a message box to display the answer. This
programming style is more difficult for other programmers to read but the
code works correctly.
- Give the function a name that uses a prefix that indicates what type of
value will be computed and returned by the function. For example, a good name
for a function whose purpose is to compute the amount of sales tax on a purchased
item would be sngComputeTax, since the returned value will be a decimal value
and therefore stored as a Single. A good name for a function whose purpose
is to round a number to there nearest integer would be intRound.
- A task that involves the computation of a single numerical value such as
computing tax or rounding a number is often handled by a general function
rather than a general procedure. If the task that you wish to place into a
procedure does NOT involve the computation of single numerical value then
you should probably use a general sub procedure instead of a function. For
example, if you need to move an object to the left on the form window, you
could use a general procedure named move (lower case letter).
- A function is different from a general procedure in that a function always
returns a single value to the procedure or function that calls it.
A general procedure does not return a value. This is why a function should
be used instead of a general procedure if the task that you intend to use
it for is simply to compute a single number (or return a single string value).
Objective #3: Understand the concept of reusability
- One motto in all computer science courses is "Reuse, Reuse, Reuse."
This means that programmers should write procedures, functions, forms, etc.
and then be able to reuse those items in other programs and projects
without having to change or modify them. For example, if you create a function
with code that computes the Pennsylvania sales tax on a user-inputted value
for one program, you could use it for the rest of your programming career.
- Programmers must always be thinking about reusability
as they design programs and algorithms. As you gain experience, you will learn
what kinds of tasks can be solved with procedures and functions that may apply
to future programming assignments. You also will learn how to separate the
code that does not change from the the code that will have to change for future
assignments. In that way, during pseudocoding, you will be able to organize
the algorithm and your efforts so that you can eventually reuse certain modules
of code.
- There are many procedures and controls at vbcode.com
and other Web sites that you can use for free or purchase. This saves a lot
of time and effort.
- Reusing code also saves time during program testing. If you had already
thoroughly tested your "sales tax" function (mentioned above), you
will not need to test that part of a program in the future. Also, reusing
code makes programs more consistent with one another and therefore more user-friendly.
Objective #4: Understand the four types of variables local, static,
module-level, and global. Be able to explain the scope, visibility, and lifetime
of each type of variable.
- There are four types of variables in Visual Basic: local, static,
module-level, and global.
- A variable's scope is determined by its visibility
and its lifetime.
- The visibility of a variable
is determined by the number of procedures, forms, and modules that can legally
use (or "see") the variable.
- The lifetime
of a variable lasts from the moment it is declared (assuming that the Option
Explicit statement is used) until the moment that it loses its value and "disappears."
When a variable is declared a few bytes of computer memory (RAM) is reserved
to store its value. When a procedure or function ends, the memory that was
used to store the value of a local variable is no longer reserved for that
variable. Eventually, a variable that is declared later in the program may
use the same exact of memory address. Module-level and static variables have
a lifetime that is longer than local variables since their memory is reserved
until the form is unloaded. Global variables, however, have the longest possible
lifetime since their memory storage area is reserved for the duration of the
whole program. Programmers should limit the lifetime of variables as much
as possible in order to use memory efficiently. Using too much memory will
slow down your program and sometimes crashes the program or computer.
Objective #5: Use an array to store data.
- An array
(also called a vector or a list) is a set of related variables.
In fact, all of the variables in the array are referenced by the same name
(the name of the array itself). For example, if you wanted to store John Doe's
five exam grades, it would be more efficient to use an array instead of 5
separate variables.
Instead of declaring 5 variables with the statement
Dim intExam1, intExam2, intExam3, intExam4,
intExam5 As Integer
You should declare an array named intExam with the statement
Dim intExam(5) As Integer
This statement creates one array that has six positions. Each position
of the array can store a separate exam value. The size
of the array intExam is said to be 6 simply because
that is how many elements it can hold. This array has 6 elements not 5 because
Visual Basic always includes an element with position (subscript) zero.
- Arrays are useful because they make it easier to program with loops and
other structures. They organize data so that it can be manipulated and processed
more efficiently. For example, instead of five separate statements that initialize
each of John Doe's exam grades to zero as in:
intExam1 = 0
intExam2 = 0
intExam3 = 0
intExam4 = 0
intExam5 = 0
It would be easier to initialize them with a For-Next loop as in:
For J = 1 To 5 '
initializing the array intExam to zero
intExam(J) = 0
Next J
- The first position of an array in Visual Basic is position 0. You can declare
variables to be as big as you would like in Visual Basic. Also, instead of
storing integers in an array (as above), you can declare an array to store
strings or any other variable data type.
- The values in an array are called elements.
The 2 in the statement
intExam(2) = 94 is called a
subscript.
The variable J in the loop example above is called an
index variable, meaning that it is being used to represent
the subscript.
- While arrays can be declared as local variables within an event procedure,
it is usually more efficient to declare an array at the top of the form just
under the Option Explicit statement. When you declare any variable in the
general declarations area of the form (the area above all procedures and functions),
the variable is called a module-level variable rather than a local
variable. It is considered to be good style to use a lower case m as a prefix
for a module-level variable. So a declaration statement for a module-level
array variable might look like this:
Dim mintExamScores(5) As Integer
- A module-level variable can be used in any procedure or function on a form
unlike local variables. If you were to try to use a local variable in any
other procedure or function from which it was declared, you would receive
a compile error (assuming that Option Explicit is at the top of your form).