Page 87 - Open Soource Technologies 304.indd
P. 87
Unit 4: VB Programming Fundamentals
varname [([subscripts])] [As [New] type]] . . .
The WithEvents keyword is valid only in class modules. This keyword specifies that varname is
an object.
Variable used to respond to events triggered by an ActiveX object. The varname identifier is the
name of the variable you are declaring. You use subscripts if you are declaring an array.
You set up the subscripts argument this way:
[lower To] upper [, [lower To] upper]
In Visual Basic, you may declare up to 60 dimensions for an array.
The New keyword enables creation of an object. If you use New when declaring the object
variable, a new instance of the object is created on first reference to it. This means you don’t have
to use the Set statement to assign the object reference. Here is an example:
Dim DataSheet As New Worksheet
The type argument specifies the data type of the variable, which may be Byte, Boolean, Integer,
Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for
fixed-length strings), Object, Variant, a user-defined type, or an object type. If you don’t specify
a type, the default is Variant, which means the variable can act as any type.
By default in Visual Basic, numeric variables are initialized to 0, variable-
length strings are initialized to a zero-length string (__), and fixed-length
strings are filled with zeros. Variant variables are initialized to Empty.
Here is an example of declaring variables using Dim:
Dim EmployeeID As Integer
Dim Employee Name As String
Dim Employee Address As String
There are many ways of declaring variables in Visual Basic. Depending on
where the variables are declared and how they are declared, we can determine
how they can be used by our application. The different ways of declaring
variables in Visual Basic are listed below and elucidated in this section.
4.3.2 Selecting Variable Types
It is time to create a new variable but what type should you use? For that matter, exactly what
type of variable types are there and what do they do? Even if you remember what types there
are, you probably wont remember the range of possible values that variable type allows.
There is a wide range of data types, so we’ll use a table here. The Visual Basic variable types
appear in Table 4.1 for reference, making selecting the right type a little easier (note that although
Visual Basic lists a Decimal variable type, that type is not yet actually supported). We also include
the literal suffix symbols for numeric values in Table 4.1 those are the suffixes you can add to
the end of values or variables to tell Visual Basic their type, like strUserFormatString$.
LOVELY PROFESSIONAL UNIVERSITY 81