CIS 230, Visual Basic
Ch. 3 Notes, page 1
Objective #1: Distinguish between variables, constants, and controls.
- If you were studying earlier versions of BASIC, you would have begun your study with an
examination of variables and constants. On the other
hand, you just spent 2 chapters studying controls and their properties. Earlier versions
of BASIC did not use controls or anything similar to controls.
- It is almost always necessary to manipulate data using variables within the code of your
VB program. For example, you program may need to computer a total of dollars earned by a
worker in a month and printout the final sum in a label's Caption property. The algorithm
that you use would subtotal the the amount of money that the worker earned in the first
week of the month with the amount that was earned in the second week. Then, the program
would add that total with the amount of money that the worker earned in the third week.
Finally, the it would necessary to add that amount to the amount of money earned in the
fourth week of the month. As you perform that addition you must temporarily store the
running total somewhere in the memory (RAM) of the computer. Once you get the final answer
you can place the value into the Caption property of a label. The location in the
computer's memory where you store the running subtotal is called a variable. Of course,
the variable "varies" or changes as the program executes.
- If you know that a number will be used within your program's algorithm many times and
would not change like the freezing point of water (O degrees Celsius) or the number of
units in a dozen (12) then you should treat that number as a constant.
Constants cannot change once they are assigned within a program.
- There are 2 types of constants actually. Named constants are ones that
you define within your program. You create the name for a named constant and you assign it
the proper value.
- Intrinsic constants are built into Visual Basic. These constants can
neither be changed or renamed. For example, the color constants (vbBlue, vbRed, etc. ) are
intrinsic ones.
- Controls are more complicated objects that have properties, that respond to user events,
and that can use built-in methods. They are much more complicated than variables and
constants. While a text box could have "12" in its Text property, this is not
identical to creating a variable and storing the value 12 there.
Objective #2: Differentiate among the various data types.
- The amount of memory that is reserved in the RAM of the computer for a
specific variable depends on the data type of the variable. The act of
specifying a specific data type for a variable and actually giving that variable a name
(also known as an identifier) is called declaring the variable. If you wish to store the
number of children in the typical American family in a variable, you logically would
choose the data type Integer. If you needed to store the amount of money that Bill Gates
earns per year, you would choose the data type Long. Although, the Long data type can only
hold whole numbers so you would have to round the Bill Gates' earnings to the nearest
dollar.
- A programmer must keep efficiency in mind when declaring variables and associating them
with data types. Data types use different amounts of memory and the amount of memory on a
computer is limited. In general, data types that can store larger numbers use more memory.
In addition, variable data types that can store a number to more precision (e.g. 3.14159
is more precise than 3.14) use more memory.
- Visual Basic does not require you to declare variables however. VB will allocate
memory for an undeclared variable at run-time but use the Variant data type.
The Variant data type is flexible and uses as much memory as necessary to store a value.
This requires more memory though than other data types and is very inefficient. You should
avoid using the Variant data type and declare all variables that you use in a program. The
best thing to do is to type Option Explicit in the general declarations
so that VB requires you to remember to declare your variables.
- Visual Basic Data Types
Data Type |
Use For |
Example |
Range |
Memory Requirements |
Boolean |
True or False values |
True |
True or False |
2 bytes |
Byte |
A single letter or digit |
'A' |
0 to 255 |
1 byte |
Currency |
Dollars and cents |
$42.35 |
-922,337,203,685,477.5808 to 922,337,203,685,477.5807 |
8 bytes |
Date |
calendar dates |
3/14/99 |
January 1, 100 to December 31, 9999 |
8 bytes |
Double |
Floating point (decimal) numbers with 14 digits of accuracy |
7.34432134567 |
-1.79769313486232E308 to -4.94065645841247E-324 |
8 bytes |
Integer |
whole numbers |
15 |
-32,768 to 32,767 |
2 bytes |
Long |
big whole numbers |
71,345,678 |
-2,147,483,648 to 2,14,483,647 |
4 bytes |
Single |
Floating point (decimal) numbers with 6 digits of accuracy |
3.14159 |
-3.402823E38 to -1.401298E-45 for negatives and 1.401298E-45 to
3.402823E38 for positives |
4 bytes |
String |
Alphanumeric data (letters and/or digits) |
"199-99-3214" |
0 to 2 billion |
1 byte per character + 10 bytes |
Variant |
any type of data |
anything |
any value up to a Double if a number 1 to 65,400
if alphanumeric |
16 bytes, if a number 22 bytes + 1 byte for each
character, if alphanumeric |
Objective #3: Apply naming conventions incorporating standards and indicating
scope and data type.
- An identifier is a programmer-created name that is used to refer to a
variable, constant, procedure, or some other structure in a program. Often, we informally
refer to identifiers as "variable names."
- Visual Basic has certain rules for identifiers. If you break one of these rules, your
program will likely have a compile error.
- Identifiers must be 1 to 255 characters in length
- Identifiers can contain letters, digits, and underscores ( _ ).
- Identifiers CANNOT contain any spaces or periods.
- Identifiers CANNOT be keywords defined in VB. (Keywords
are sometimes called "reserved words.")
- VB programmers must obey the VB rules cited above. In addition to these rules though,
certain conventions have been adopted by VB programmers that you should
also follow. Note that you may have to read a coworker's code someday and vice versa.
Following conventions such as this one makes it easier to understand other programmers'
code.
- Identifiers must be meaningful and descriptive. The purpose of the variable or procedure
should be indicated by its name. Never use single letters as variable names (unless it is
an index or loop variable.) Only abbreviate words within a variable name if you think
others will understand the abbreviation.
- If multiple words are joined to make an identifier more descriptive, you should
capitalize each word. This is sometimes called the InterCap method. For
example, the identifier intSumProduced should be used instead of intsumproduced or
intSumproduced .
- The identifier should begin with a lowercase prefix that indicates the variable's data
type. The VB programming community has adopted a set of prefixes for the VB data types.
Prefix |
Data Type |
bln |
Boolean |
cur |
Currency |
dbl |
Double |
dtm |
Date |
int |
Integer |
lng |
Long |
sng |
Single |
str |
String |
vnt |
Variant |
- You can find these coding conventions and others on the Web at Microsoft's Web site ( http://www.microsoft.com/msdn )
- Intrinsic constants use two-character prefixes to indicate that they are intrinsic as
opposed to named constants. Named constants use the three-letter,
lowercase character prefixes that represent data types as in the chart above however you
should type the rest of the identifier with uppercase letters. For example, a named
constant that stands for the PA sales tax rate might be named sngPA_TAX_RATE. Notice that
the underscore character should be used to separate multiple words within the identifier
for named constants.
Objective #4: Declare variables using the Dim statement.
- When you declare a variable, you are reserving memory so that value that the variable
will eventually hold can be stored. You need to use a Dim statement to do
so. Dim stands for "dimension" which implies that you are
dimensioning the variable to a certain size to hold a specific data type. The
statement Dim intTotalProduced As Integer
dimensions the variable intTotalProduced to the size 2 bytes so that it can hold an
integer value.
Objective #5: Select the appropriate scope for variables and constants.
- A variable (or constant) can be only be accessed from within areas of your VB project
depending on the scope that you chose for the variable when it was
declared. There are three levels of scope, global, module level,
or local.
- A global variable may be used in ALL procedures of a project. Usually it is wise to avoid overusing global variables
even though they seem convenient. It is a conventional to begin a global variable's
identifier with a lowercase g.
- A variable with module level scope can be used anywhere within the
module (a form or a code module). That is it can be used in any number of procedures that
happen to be located in the particular module. It is conventional to begin a module level
variable's identifier with a lowercase m.
- A local variable can only be used within the specific procedure where
it is declared.
- The scope of the variable determines its visibility. The visibility of
a variable refers to whether or not a variable "can be seen" by a particular
procedure.
- The scope of a variable is determined by where you place its Dim statement. It is
conventional to place the Dim statement at the top of the procedure if its a local
variable and in the general declarations section of a module if it has module level scope.
Objective #6: Convert text input to numeric values using the Val function.
- When a user inputs alphanumeric characters into a text box on a form, he or she is
actually placing the characters into the Text property of that text box. The Text property
of a text box is treated as a character string. Even if the user is asked to enter a
number such as the number of items purchased the entered digits are treated as one string.
Unfortunately you probably would want to perform arithmetic on the value entered by the
user but it is an error to perform arithmetic on a string.
- The Text property of the text box must be converted to a value which can be used in an
arithmetic expression. Use the Val function to convert a string into a
numerical value. The statement intTotalItems
= Val(txtItems) would make the conversion. Remember that
the Text property of the text box txtItems is the default property so txtItems.Text is
unnecessary in the reference. The variable intTotalItems will contain an actual numerical
value that can be added, subtracted, multiplied, etc. Note that if the Text property of
txtItems cannot be turned into a valid number, the Val function may return a zero.
Actually the Val function reads the Text property from left to right turning digits,
decimal points, and positive or negative signs into numbers until it reaches an invalid
character. Examples: Val("123.4#") = 123.4
Val("-13") = -13
Val(#903) = 0
Objective #7: Perform calculations using variables and constants.
- When performing calculations within an expression in your code you must take into
account the order of operations. Many people learned "Please Excuse
My Dear Aunt Sally" in elementary or junior high school. This reminds you to execute
the following mathematical operations in this order: Parentheses,
Exponentiation, Multiplication, Division, Addition, and Subtraction. However,
multiplication and division should be evaluated from left to right within the expression
as well as addition and subtraction. For example, 10 - 3 + 4 = 11 not 3.
- You should add parentheses if necessary in order to make sure that your expression
evaluates correctly.
- Assignment statements evaluate from right to left. So you must evaluate
the expression to the right of the assignment operator (the equal sign,
=) and realize that the resulting value will be stored in the variable to the left of the
assignment operator. However, you may assign a value to a label Caption property or a text
box Text property.
Objective #8: Format values for output using the formatting functions.
- It is important to make sure that results of an expression are formatted
nicely if the output is to be displayed to the user. Visual Basic provides a number of
formatting functions that can be used to display values nicely.
- The FormatCurrency function returns a string of characters formatted as
a monetary amount with a dollar sign, commas if necessary, and two positions to the right
of a decimal point. Formerly with older version of BASIC this sometimes was much more
difficult than using one simple function. For example,
FormatCurrency(1345.236) = $1,345.24
- The FormatNumber function works similarly as the FormatCurrency
function except that the dollar sign is not outputted. It is easy to prevent the numbers
to the right of the decimal from being displayed by adding a second argument. For example,
FormatNumber(1345.236, 0) = 1,345
- The FormatPercent function can be used to automatically multiply the
argument by 100 and add a percent sign. For example,
FormatPercent(.8241, 1) = 82.4% where the second argument
indicates that one decimal place is to be displayed.
- The FormatDateTime function works along with predefined formats to
display dates and/or times. For example,
FormatDateTime("9/10/98", vbGeneralDate) = 9/10/98 5:23:12 PM
Other named formats are vbLongDate, vbShortDate, vbLongTime, and vbShortTime.
Objective #9: Accumulate sums and generate counts.
- Often it is necessary to obtain a subtotal within a program's code. A statement like
mintTotalPurchased =
mintTotalPurchased + intPurchased is
used as an accumulator statement.
- While the statement above looks illegal syntactically, it is quite practical. The
expression to the left of the assignment operator (the equals symbol) is first evaluated.
The resulting sum is then assigned into the named variable, mintTotalPurchased. Note that
a variable used to hold a subtotal such as mintTotalPurchased would often have module
level or even a global scope.
- Often it is convenient to count how many times something has happened within one's
program. A counter statement such as mintCount = mintCount + 1
works similarly to an accumulator statement. The value 1 is added to mintCount each time
the statement is evaluated.
- After you learn how to use loops in Visual Basic, accumulator and counter statements
will be very useful.
Objective #10: Format data for output.
- You should read your textbook closely and look up formatting functions in VB's online
documentation to learn more about formatting data for output. You should also experiment
with the formatting functions in order to understand how VB can be manipulated to produce
attractively formatted output.
Objective #11: Modify the environment to require Option Explicit.
- Choose the menu option, Tools/Options..., and then checkmark the Require
Variable Declaration under the Editor tab in order to have VB automatically
place the statement Option Explicit in every module that
you insert into every project.
- Making this change requires you to declare all named variables and constants
using Dim statements. This will prevent a number of logical and other errors.
CIS 230 Home Page | Mr. Minich's Education Home Page | Minich.com Web Design