Programming With Visual Basic Chapter 4
Programming With Visual Basic Chapter 4
Programming With Visual Basic Chapter 4
FACULTY OF ENGINEERING
MECHANICAL ENGINEERING DEPARTMENT
CMPE 106
FUNDAMENTALS OF COMPUTING
LECTURE NOTES
PROGRAMMING WITH
VISUAL BASIC 6.0
CHAPTER 4
VISUAL BASIC VARIABLES AND
OPERATORS
PREPARED BY
MERT BAL
SPRING 2004-2005
CMPE 106 -VISUAL BASIC 6.0 Lecture Notes Chapter 4 - Page...1/15
Prepared by Mert Bal - Spring 2004-05
This program statement sounds a note from your computers speaker. Or, a statement can be a
combination of elements, such as the statement showing in this illustration, which assigns the current
system time to a label caption.
Statement Syntax
The anatomy of a program statement is syntax, the rules of construction that you must use when you
build a program statement. Visual Basic shares many of its syntax rules with earlier versions of the
Basic programming language and with other language compilers.
The trick to writing good program statements is learning the syntax of the most useful language
elements. Then, it's a matter of using those elements correctly to process the data in your program.
Fortunately, Visual Basic does a lot of the toughest work for you. The time you spend writing program
code will be relatively short, and the results can be used again in future programs.
In the following topics, youll learn the most important Visual Basic keywords and program
statements. Youll find that they complement the programming skills youve already learned rather
nicelyand they can help you to write powerful programs in the future.
4.1.2.Creating Variables
Declaring a variable is the process of creating a variable in your Visual Basic program code. You can
do this explicitly with the Dim keyword or implicitly by typing a new variable name in a program
statement.
This section includes the following topics:
Explicit Declarations
Implicit Declarations
Explicit Declarations
In Visual Basic, one of the ways to create a variable is to declare it explicitly. Typically, you declare a
variable explicitly before you use the variable (usually at the beginning of an event procedure). You
declare the variable by typing a Dim (dimension) statement and the variable name. For example, the
following statement creates space for a program variable named LastName:
Dim LastName
Typing the statement reserves room for the variable in memory when the program runs, and lets
Visual Basic know what type of data it should expect to see later.
Assignment Operator
After you declare a variable, you are free to assign information to it in your code by using the
assignment operator (=). This statement assigns the name Jefferson to the LastName variable:
LastName = "Jefferson"
After this assignment, you can substitute the LastName variable for the name Jefferson in your
code. For example, this assignment statement would display Jefferson in the first label (Label1) on
your form:
Label1.Caption = LastName
Implicit Declarations
You can also declare a variable without the Dim statement; this process is called implicit declaration.
To declare a variable implicitly, you simply use the variable on its own and skip the Dim statement
altogether. Here's an example:
LastName = "Charles V"
LastName = "Smart"
Label1.Caption = LastName
LastName = 99
Label2.Caption = LastName
4.1.3.Using Functions
In this section, you learn how to use these three special Visual Basic keywords, called functions, in a
program.
The MsgBox function, which displays output in a popup dialog box.
The InputBox function, which prompts the user to supply input in a dialog box.
Mathematical functions, with which Visual Basic calculates new values.
This section includes the following topics:
What is a Function?
Using the MsgBox Function
Using the InputBox Function
Demonstration: Using InputBox and MsgBox
Mathematical Functions
What is a Function?
A Visual Basic function is a statement that performs meaningful work (such as prompting the user
for information) and returns a value to the program. The value that a Visual Basic function returns can
be assigned to a variable, a property, another statement, or another function. A Visual Basic function
is different from a Function procedure that you write yourself.
Visual Basic functions often include one or more arguments that define their activities. For example,
the InputBox function uses the Prompt variable to display a dialog box with instructions for the user.
When a function uses one or more arguments, they are separated by commas, and the whole group
of arguments is enclosed in parentheses. The following statement shows a function call that has two
arguments:
FullName = InputBox$(Prompt, Title)
The Prompt argument takes a string that displays a prompt for the user in the Input box, and the
Title argument takes a string that displays a title in the input box title bar.
For more information about these optional arguments (including the different buttons you can use in a
message box), search for MsgBox function in the Visual Basic online Help.
Mathematical Functions
Now and then, you might want to do a little number crunching in your programs. You may need to
convert a value to a different type, calculate a complex mathematical expression, or introduce
randomness to your programs.
Visual Basic functions can help you work with numbers in your formulas. As with any function,
mathematical functions appear in a program statement and return a value to the program. In the
following table, the argument n represents the number, variable, or expression you want the function
to evaluate.
Function
Abs(n)
Atn(n)
Cos(n)
Exp(n)
Int(n)
Rnd(n)
Sgn(n)
Sin(n)
Sqr(n)
Str(n )
Tan(n)
Val(n)
Purpose
For example, the following formula uses the Sqr (square root) function to calculate the hypotenuse of
a triangle by using the variables a and b:
Hypotenuse = Sqr(a ^ 2 + b ^ 2)
CMPE 106 -VISUAL BASIC 6.0 Lecture Notes Chapter 4 - Page...6/15
Prepared by Mert Bal - Spring 2004-05
Size
Range
Byte
1 byte
0 through255
Integer
2 bytes
Long
4 bytes
Single
4 bytes
2,147,483,648 through
2,147,483,647
-3.402823E38 to -1.401298E -45
for negative values;1.401298E -45
to 3.402823E38 for positive
values
Double
8 bytes
Currency
8 bytes
10 bytes
2 bytes
Date
8 bytes
Variant
Note If you want to place the Type statement in the Declarations section of a form module, you must
precede the Type statement with the Private keyword.
This looks a little like setting a property, doesnt it? Visual Basic uses the same notation for the
relationship between objects and properties as it uses for the relationship between user-defined data
types and their component variables.
4.2.3.Constants
If a variable in your program contains a value that never changes, you should consider storing the
value as a constant instead of as a variable. A constant is a meaningful name that takes the place of
a number or text string that doesnt change (such as , a fixed mathematical quantity.)
Advantages of using constants include:
Making program code more readable
Saving memory
Making program -wide changes easier to accomplish.
Displaying Constants
The following program statement shows how you can display the value contained in the Pi constant
with an object named Label1:
Label1.Caption = Pi
Constants are very useful in program code, especially when your program includes mathematical
formulas, such as Area = 2r2. The next section describes how you can use operators and variables
to write mathematical formulas.
*
/
Mathematical operation
Addition
Subtraction
Multiplication
Division (floating-point)
For example, the following program statements use the addition and multiplication operators to
calculate the total cost of a $250 bicycle including 8.1% sales tax:
Dim BicycleCost, TotalPrice
Const SalesTaxRate = 0.081
BicycleCost = 250
TotalPrice = BicycleCost * SalesTaxRate + BicycleCost
4.3.2.Advanced Operators
In addition to the four basic arithmetic operators, Visual Basic includes four advanced operators,
which are useful in special-purpose mathematical formulas and text processing applications:
Operator
\
Mod
^
&
Mathematical operation
For example, the following program statement uses the Time and Date functions and the string
concatenation operator (&) to build a sentence from four string values:
Label1.Caption = "The current time is " & Time & " on " & Date
When you execute the program statement, the Label1 object displays output in the following format:
The current time is 5:14:16 PM on 12/5/97
4.3.3.Operator Precedence
In the last few sections, you experimented with seven mathematical operators and one string
operator. In Visual Basic, you can mix as many mathematical operators in a formula as you likeas
long as an operator separates each numeric variable and expression. For example, this is an
acceptable Visual Basic formula:
Total = 10 + 15 * 2 / 4 ^ 2
The formula processes several values and assigns the result to a variable named Total. But you're
probably wondering how Visual Basic evaluates this expression. After all, there's no way to tell which
mathematical operators Visual Basic uses first to solve the formula. In this example, the order of
evaluation matters a great deal.
Visual Basic solves this dilemma by using a specific order of precedence for mathematical operations.
When Visual Basic evaluates an expression that contains more than one operator, the order of
precedence supplies rules that determine which operators Visual Basic evaluates first.
The rules can be summarized by these principles:
Use the operators in the order of precedence.
For operators on the same precedence level, evaluate from left to right as they appear in an
expression.
The following table lists mathematical operators in their order of precedence:
Order of precedence
Symbols
Operator
First
()
Exponentiation (raising a
number to a power)
*/
Integer division
Mod
Remainder division
Last
&
String concatenation
Exponentiation
Total = 10 + 15 * 2 / 16 Multiplication
Total = 10 + 30 / 16
Division
Total = 10 + 1.875
Addition
Visual Basic determines the expression between the parentheses (- 7) before doing the
exponentiation even though exponentiation has a higher order of precedence than
subtraction and multiplication do.
Nested Parentheses
You can further refine the calculation by placing nested parentheses in the formula. Here's the same
formula with a new twist:
Number = ((8 - 5) * 3) ^ 2
Embedding (nesting) the second set of parentheses in the formula directs Visual Basic to calculate
the formula this way:
Number
Number
Number
Number
=
=
=
=
((8 - 5) * 3) ^ 2
(3 * 3) ^ 2
9 ^ 2
81
As you can see, the results produced by the two formulas are different: 49 in the first formula and 81
in the second. So, adding parentheses can change the result of a mathematical operation as well as
make it easier to read.
Start a new project. The idea of this project is to determine how much you save by making monthly
deposits into a savings account. For those interested, the mathematical formula used is:
F = D [ (1 + I)M - 1] / I
where
F - Final amount
D - Monthly deposit amount
I - Monthly interest rate
M - Number of months
2.
Place 4 label boxes, 4 text boxes, and 2 command buttons on the form. It should look something like
this:
3.
1-Fixed Single
Savings Account
frmSavings
Label1:
Caption
Monthly Deposit
Label2:
Caption
Yearly Interest
Label3:
Caption
Number of Months
Label4:
Caption
Final Balance
Text1:
Text
Name
[Blank]
txtDeposit
Text2:
Text
Name
[Blank]
txtInterest
Text3:
Text
Name
[Blank]
txtMonths
Text4:
Text
Name
[Blank]
txtFinal
Command1:
Caption
Name
&Calculate
cmdCalculate
Command2:
Caption
Name
E&xit
cmdExit
4.
Declare four variables in the general declarations area of your form. This makes them available to
all the form procedures:
Option Explicit
Dim Deposit As Single
Dim Interest As Single
Dim Months As Single
Dim Final As Single
The Option Explicit statement forces us to declare all variables.
5.
This code reads the three input values (monthly deposit, interest rate, number of months) from the text
boxes, computes the final balance using the provided formula, and puts that result in a text box.
6.
7.
Play with the program. Make sure it works properly. Save the project.
-END OF CHAPTER 4-