Variables
Variables
Store information temporarily
Have a short easy to remember name
used by the programmer
Declaring a Variable
Dim Statement
Used to declare a variable – gives the variable a
name, reserves room in memory, tells the compiler what kind (type) of
data it will hold (also called variable typing).
Usually done at the top of a procedure or code
module
Dim LastName as String
Later the variable can have contents deposited to
it with the assignment statement
LastName=”Jefferson”
And later still, the variables contents can be
dropped into a VB control
Label1.Text = LastName
Or passed as an argument to a procedure or
function. The variable Prompt is passed to the InputBox function.
The results as assigned to the FullName variable.
Dim FirstName as
String
MsgBox("Mr. " & LastName “please enter
your first name.”)
FirstName =
InputBox(Prompt)
Variable Name Rules
-
Start with a letter or underscore
-
Contain letters, underscores, numbers – no
special characters, no punctuation
-
Limit is 255 characters, but 33 is more
reasonable
-
Don’t use VB keywords, objects or properties as
variable names
-
“Camel Casing” is common – use more than one
word, but capitalize the first letter of each
-
Use of a prefix is common – strLastName says
the variable is a string
Variable Types
Here are the most common types to start out
with. There are many others.
String –
treat data as separate characters. No math will be done with this.
Integer –
positive whole numbers.
Single –
numbers with places right of the decimal point, positive and
negative.
Declare More Than One Variable In A Single Statement
You can declare more than one variable in a
single statement as long as they are the same type, and if you
separate the names with a comma.
Dim LastName, FirstName
as String
Constants
Constants are variables with a set value which
will never change. Examples include Pi. These are given the type
Const.
Const Pi as Double =
3.14159265
When they are declared Public, they are
available to all objects, functions and code modules.
Public Const Pi as
Double = 3.14159265
UDTs
You can make your own data type as well, which is
called a User-Defined Type. These are used when a set of variables
are often used together.
Structure FullName
Dim First as String
Dim Middle as String
Dim Last as String
The lines above define a user defined type named
FullName. This data type store the three variables under it.
Dim Student as FullName
Student.First =
“John”
The lines above create a new variable called
Student. This variable has the type FullName which is a user defined
type consisting of three variables. The second statement assigns the
variable First which is part of Student with the word John.
It’s just another way of working with variables
that might be helpful in certain cases.
|