Wyo VB - Ch. 3 Notes
Objective #1: Use Dim statements to declare variables and understand
the physical process of memory (RAM) allocation.
- You should get used to declaring all variables in a program with Dim
statements. Such a statement is called a declaration statement. For example,
Dim sngPrice As Single
causes 4 bytes of memory (RAM) to be reserved for the value of the variable
sngPrice. Furthermore, VB automatically initializes the Single variable to
the value 0.0.
- Technically, VB does not require you to declare any variables. However,
you should use the
Option Explicit
statement at the top of each form to force yourself to declare variables in
all programs. It is recommended that you declare all variables though. Other
computer programming languages such as C++ require programmers to declare
all variables before using them.
- When VB executes a declaration statement, the variable is allocated a certain
number of bytes according to the data type specified in the declaration statement.
Actually, if a programmer simply uses a declaration statement such as
Dim sngPrice
VB will treat the variable as a Variant data type. The common prefixes that
most programmers use with variable names have no actual effect on the data
type.
Objective #2: Understand each of the basic data types used by Visual
Basic.
- You must carefully choose the data type for each variable that you
declare in your program.You must use a data type that can store numbers that
are in the range of values that you expect the variable to possibly
hold during a program's execution. Try not to choose data types that are way
too large or you will be guilty of wasting memory space.
- For example, if you needed to store the number of hamburgers sold at a
McDonald's restaurant in one day, you should probably use a variable with
the Integer data type (to allow for a maximum number of 32,767 hamburgers
sold). On the other hand, if you needed to store the number of hamburgers
sold on a given day by ALL of the McDonalds restaurants in the U.S., it
would probably be necessary to use a variable with the Long data type (to
allow for maximum number of 2,147,483, 647 hamburgers).
data type
|
prefix |
characteristics
|
range
|
size (bytes)
|
|
|
|
|
|
Byte |
byt
|
a single character (letter, symbols, or digit)
|
0 to 255 |
1 |
Integer |
int
|
whole numbers only |
-32,768 to 32,767 |
2 |
Long |
lng
|
whole numbers only |
-2,147,483,648 to 2,147,483,647 |
4 |
Single |
sng
|
decimal numbers |
-3.4E38 to -1.4E-45 for negative
values; 1.4E-45 to 3.4E38 for positive values |
4 |
Double |
dbl
|
large, decimal numbers |
-1.8E308 to -4.9E-324 for
negative values; 4.9E-324 to 1.8E308 for positive values |
8 |
Currency |
cur
|
more precise than Single or Double for representing
money; unlike Single, it accurately rounds to the fourth decimal place
(ten-thousandth's) |
+/- 922 trillion to 4 decimal
places |
8 |
String |
str
|
text, symbols, digits |
0 to about 65,000 bytes |
varies |
Variant |
var
|
numbers or strings, uses much memory; avoid
using if possible |
variable |
varies |
- You should no longer use the Currency or Variant data types however since
the latest version of Visual Basic (version 7) does not support or allow those
data types.
- It is dangerous to mix data types in Visual Basic as in the assignment statement,
sngTotalPrice = intApplesPrice + sngCandyBarPrice
since an Integer and a Single are being added, there is no guarantee that
VB will be able to perform this mixed-mode addition. Realize that you
are asking VB to add a 2-byte variable to a 4-byte variable! That is sort
of like mixing apples and oranges. Usually, VB will compute a mixed mode expression
that involves an Integer variable and a Single variable and round the result.
If the expression is being stored to an Integer variable, the result will
be rounded! If the expression is being stored to a Single variable the result
will have the expected decimal digits. Note that you can't always assume that
a programming language allows you to mix data types within expressions. Sometimestruncation
will occur causing the decimal portion of a computed number to be lost.
- The reason why an Integer can only store a whole number as high as 32767
is because of the fact that an Integer is 2 bytes in size. Since 2 bytes is
equivalent to 16 bits, the largest binary value that can be stored in an Integer
is 1111 1111 1111 1111. However, the leading
(leftmost) bit (known as the sign bit) is used to keep track of whether
the value is positive or negative, so only 15 bits are used to store the variable's
actual value. Since 2^15 is 32768, you may think that 32768 should be possible
as an Integer value. But since the value 0 must be a possible value, 32767
(which is 2^15 - 1) is the largest value that can be stored in an Integer
variable. On the other hand, -32768 is the least (most negative) value that
can be stored in an Integer.
- If you try to add one or more to an Integer variable that has the value
32767 an overflow error occurs since the maximum value permitted for
an integer is 32767.
Objective #3: Know how to use the InterCap
method and the appropriate data type prefixes when naming variables.
- Use sensible and meaningful variable names that make sense. Do not use single
letters as variable names like x or y. A program that uses meaningful, descriptive
variable names is called self-documenting. This is done so that others (teachers,
coworkers, and even yourself) can understand your program easier.
- Variable names along with function and procedure names (we'll study these
later) are also considered to be identifiers.
- It is conventional though not required by the VB compiler or interpreter
to begin a variable with a prefix that identifies its data type. See the chart
above for the standard prefixes. So a good variable name might be intRuns
to store the number of runs scored in a baseball game program. However, you
may use multiple words to more fully describe the variable's purpose. A better
variable name might be intRunsScored. Each word in the variable name (besides
the prefix) should be capitalized. This method of capitalizing the words in
an identifier is known as the InterCap method of naming variables.
- In most programming languages, including VB, an identifier must begin with
a letter and not a digit or a symbol. Thus the variable names 2Many
or %More would not be valid. Technically, the variable name int2Many
would be valid since an identifier can include digits as long as a letter
is the first character. You cannot include a space within an identifier either.
Therefore the variable name intRuns Scored would not be valid. To be
safe, you should not use more than 31 characters in an identifier either.
- Examples of good variable names:
- intNumStudents
- sngSalary
- sngTotalPrice
- strFirstName
Objective #4: Use the order of operations to evaluate expressions and
to write proper expressions.
- Remember "Please Excuse
My Dear
Aunt Sally"
- Multiplication & Division are tie, so they must be evaluated from left
to right across the expression. That is, it is quite possible to be forced
to evaluate a division operation before a multiplication in certain instances.
- Evaluate the expression, 10 / 5 * 2. Your answer should be 4
and not 1 because the division must be applied before the multiplication.
- 24 / 8 * 4 = 12 (not 0.75)
- 20 / 2 * 5 = 50 (not 2)
- 2 * 2 * 2 / 2 * 2 = 8 (not 2)
- TRY THIS ONE: 36 / 18 * 2 = ?
- Similarly, addition & subtraction are tie, so they must be evaluated
from left to right across the expression as well.
- 10 - 5 + 5 = 10 (not 0)
- 100 - 3 + 97 = 194 (not 0)
- 50 + 60 - 3 + 100 = 207 (not 7)
- TRY THIS ONE: 100 - 5 + 5 - 5 +
5 = ?
- Expressions are groups of operators and operands that
can be evaluated.
- Examples of expressions:
- 9 + x - 12
- (intGame1 + intGame2 + intGame3) / 3
- Operators
- unary operators
- binary operators
- + is the addition operator
- - is the subtraction operator
- / is the division operator
- * is the multiplication operator
- ^ is the exponent operator (e.g. 2 ^ 3 is equal to 8 since 2
to the third power is 8)
- Operands are the numbers or variables that are bound by the operators.
- In the expression x
+ 3 both x and
3 are operands.
Objective #5: Be able to translate algebraic expressions to Basic.
- Mathematical notation must be written on a single line of code in Basic.
- Insert parentheses where necessary in order to preserve the correct evaluation
(that is, you must realize that Basic obeys the order of operations).
The rule-of-thumb is to add extra parenthesis when you are in doubt if they
are required or not. But note, though, that later in the school year, your
teacher may deduct points for unnecessary parentheses in your code.
- Note that Basic computes the two examples below differently behind-the-scenes,
even though the final answer may be the same in both cases:
- sngFahr = 9 * sngCel / 5 + 32
- sngFahr = 9 / 5 * sngCel + 32
Objective #6: Know how to write assignment statements to evaluate expressions
and assign the resulting values to variables and properties.
- Assignment statements evaluate the expression on the right-hand side of
the assignment operator (the equals symbol) and assigns the resulting
value into the variable on the left-hand side of the assignment operator
- Examples:
- sngRate = 0.035
- curInterest = curPrincipal * sngRate * intTime
(the * refers to multiplication)
- strMsg = "Enter a Value: "
(Notice that there is a space after the colon for aesthetic reasons)
- DO NOT CODE THE FOLLOWING:
x + 8 = y which is "backwards" as
an assignment statement.
- You must be careful distinguish between string data and numeric data (which
includes integer, long, single, double, & currency). For example, the
string "13" is not equivalent to the value, 13, that may be stored
in a variable of the integer datatype. The double quotations are used to show
that the string "13" cannot be added, subtracted, etc. from another
numeric variable. The quotations acts as delimiters.
- With the Val command, one could change "13" into 13 as in
Val("13") = 13.
- Similarly, one could change the numerical value, 14, into a string
with
Str(14) = "14".
Objective #7: Know how to set break points, examine values of variables
and expressions in the Debug window, and single-step through programs.
- Simply highlight the line of code at which you want to set the break point
and then click the "Toggle Breakpoint" icon on the toolbar.
- Visual Basic will stop executing the code at that line and allow you to
type Print statements into the Debug window. If the Debug window isn't
open, select View/Debug Window or click Control-G.
- To single-step through the program once you have stopped its execution at
a break point, click the "Step Into" icon on the toolbar. You can
continue to check variable values by typing Print statements into the Debug
window.
Objective #8: Be familiar with the naming convention used for controls.
- You must use the InterCap method with the conventional prefixes
when naming controls and objects. Always begin a control's name with the correct
prefix (3 lowercase letters) that identify the type of control that you are
naming.
Object |
Prefix |
Example |
Form |
frm |
frmUserEntry |
Command button |
cmd |
cmdExit |
Text box |
txt |
txtDescription |
Label |
lbl |
lblSum |
Option button |
opt |
optSingle |
Check box |
chk |
chkSummary |
Frame |
fra |
fraChoices |
Horizontal scroll bar |
hsb |
hsbSpeed |
Vertical scroll bar |
vsb |
vsbHeight |
Image |
img |
imgDesign |
Picture box |
pic |
picFace |
Combo box |
cbo |
cboList |
List box |
lst |
lstEntries |
Line |
lin |
lnHorizon |
Menu |
mnu |
mnuFile |
Shape |
shp |
shpRectangle |
Common Dialog |
dlg |
dlgCommon |
- For some labels that you include on a form and occasionally other objects,
you may use the default names (e.g. Label1, Label2) that are assigned by Visual
Basic. If you do not refer to an object within your code, then you can use
its default name.
Objective #10: Be able to change the properties of controls.
- Do not confuse the Text property with the Name property of text boxes. The
Text property is what the user can see and possibly modify on the screen.
The Name property is what you use as the programmer to organize your program.
- Follow the established naming conventions when you assign your own names
to objects such as textboxes, command buttons, and labels. Note that the first
three letters of the Name property are all lowercase and identify what type
of object the item is. The other word(s) is supplied by the programmer to
identify the purpose of the object in the program.
- Examples: cmdExit, lblClassPeriod, txtLastName
- You may use some of the names of objects that are assigned by Visual
Basic by default. Note that these names do not follow the naming convention
explained above. But, if your program (that is, project) includes numerous
objects of the same type, it is wise to provide your own, more meaningful,
names.
- Some properties only allow True and False values. Experiment with those
properties to learn what these settings do. Technically, any nonzero numerical
value is equivalent to True and zero is equivalent to False.
Objective #11: Explain how Visual Basic responds to the Click event.
- The Click event adds user interactivity to a program. You must add
code to the objects such as command buttons that incorporate this event.
Objective #12: Explain the term event-driven programming.
- Visual Basic makes it easy to create event-driven programs.
An event-driven program is one which responds to users' actions such
as mouse clicks and mouse movement. Before widespread use of the desktop computer
mouse in the late 1980's, it made little sense to create such programs. Nowadays,
computer users have more control over the flow of the program and the order
of the execution of different tasks. This places new demands on programmers,
however. It is important to carefully design a practical and consistent environment
when writing VB programs.

- Formerly, programming languages such as older versions of Basic, Pascal,
C, FORTRAN, and COBOL were considered to be procedural. The
programmer simply wrote lines of code that executed with a sequential
flow of control. The compiler or interpreter determined the order
of execution of different tasks based on the programmer's original design.
Such programs were not as interactive as modern Visual Basic event-driven
ones. However, sometimes user interactivity is a hindrance to effective program
execution.
Objective #13: Properly design the user interface using objects' TabIndex
properties, the SetFocus method, and the focus along with keyboard shortcuts
and Clear buttons.
- The TabIndex Property is used to give the user a more user-friendly
experience while executing the program. By setting an object's TabIndex Property
to 0, a programmer can ensure that the user can immediately enter information
into that object (usually a textbox or label). For example, a programmer may
want to set the TabIndex Property of a command button to 0 to highlight that
button to allow the user to simply press the Enter key to continue with the
execution of a program.
- Objects such as command buttons and textboxes have the property called TabIndex.
As you create objects and place them on the form, these objects' TabIndex
properties are set to the numbers 0, 1, 2, etc. Only one object can have a
given a TabIndex property setting of 0, only one object can have a setting
of 1, etc. Whichever object has the lowest TabIndex property will first have
the focus. By setting a form's objects sequential TabIndex properties
(say, from 0 to 7), the programmer can lead the user in a sensible, logical
manner during the program execution.
- The focus refers to the object which is selected at any given moment
during a program's execution. For example, if the cursor is blinking within
a text box, allowing the user to input a number there by typing on the keyboard,
that text box is said to have the focus. However, if the user presses the
Tab key on the keyboard, then the focus will jump to the object that has the
next greatest TabIndex property. Once the user moves the focus to the object
with the greatest TabIndex property, pressing the Tab key will cause the focus
to return to the original object with the smallest TabIndex property setting
(usually 0, not 1).
- You should carefully create objects and place them on a form in the order
that you wish the user to be able to access them via the Tab key. In that
way, you will not have to manually set the TabIndex properties.
- You should place the ampersand symbol ( & ) before carefully chosen
letters within the Captions of command buttons and other objects so that the
user can use keyboard shortcuts to activate those objects instead of
clicking with the mouse. Some users prefer using the keyboard rather than
the mouse. It is the programmer's responsibility to allow for multiple modes
of input. Furthermore, you should follow standard Windows conventions when
choosing which letter to set as an object's keyboard shortcut. For example,
the 'x' in Exit is standard.
- You should place a Clear command button as well as an Exit command
buttons when appropriate for a more user-friendly, conventional interface.
Within the Clear command button, you usually change the Text properties of
text boxes to the null string (aka empty string, ""). Within the
Exit button, you should first unload the form with the statement Unload
Me before typing
the statement End
- The SetFocus method can be used to purposefully place the focus on
a certain object. For example, if you wish the focus to be placed on the Exit
button at a particular point in a program's execution so that the user only
has to press the Enter key to exit the program, you would use the statement,
cmdExit.SetFocus
- One command button on a form should have its Default property set
to True. This command button will appear shadowed and it's Click event will
respond if the user presses the Enter key. You should also set the Cancel
property to True for one command button on the form. An obvious candidate
for this setting would be a cmdClear or even a cmdExit command button. This
command button's Click event will execute if the user presses the Escape (Esc)
key in the upper left corner of any keyboard.