VISUAL BASIC FUNDAMENTALS
2
Visual Basic Naming Rules Use the following rules when you name procedures, constants, variables, and arguments in a Visual Basic module: • You must use a letter as the first character. • • •
You can’t use a space, period (.), exclamation mark ( ! ), or the characters @, &, $, # in the name. Name can’t exceed 255 characters in length. You can’t repeat names within the same level of scope. For example, you can’t declare two variables named age within the same procedure. However, you can declare a private variable named age and a procedure-level variable named age within the same module.
Note: Visual Basic isn’t case-sensitive, but it preserves the capitalization in the statement where the name is declared.
Adding Comments Comments provide a convenient means to document a program. Visual Basic ignores comments when it compiles your program. Comment lines begin with a single apostrophe ( ' ), followed by a textual message, and can be added anywhere in a procedure. By default, comments are displayed as green text. Example:
‘Program to calculate the sum of two numbers Sum = num1 + num2
Assignment Statements Assignment statements assign a value or expression to a variable or constant. Assignment statements always include an equal sign (=). Some examples of assignment statements are:
youName = InputBox(“What is your name?”) age = currentDate – birthDate message = “Show me the money”
Numeric Constants Numbers are referred to as numeric constants in Visual Basic. Most numeric constants are expressed as integers (whole numbers that do not contain a decimal point or an exponent), long integers (similar to integers with an extended range), single-precision real quantities (numbers that include a decimal point, an exponent, or both), or double-precision real quantities (similar to single-precision real quantities with an extended range and greater precision). The following rules apply to numeric constants: 1. 2.
Commas cannot appear anywhere in a numeric constant. A numeric constant may be preceded by a + or a – sign. The constant is understood to be positive if a sign does not appear.
Information and Communication Technology Department Palompon Institute of Technology
14
VISUAL BASIC FUNDAMENTALS
3. 4. 5.
6.
2
An integer constant occupies two bytes. It must fall within the range -32,768 to 32,767. It cannot contain either a decimal point or an exponent. A long integer constant occupies four bytes. It must fall within the range -2,147,483,648 to 2,147,483,647. It cannot contain either a decimal point or an exponent. A single-precision real constant occupies four bytes. It can include a decimal point and as many as seven significant figures. A single-precision real constant can include an exponent if desired. Exponential notation is similar to scientific notation, except that the base 10 is replaced by the letter E. Thus, the quantity 1.2 x 10-3 could be written as 1.2E-3. The exponent itself can be either positive or negative, but it must be a whole number, i.e., it cannot contain a decimal point. A double-precision real constant occupies eight bytes. It can include a decimal point and as many as fifteen significant figures. A double-precision real constant can include an exponent if desired. Double-precision exponential notation is similar to scientific notation, except that the base 10 is replaced by the letter D. Thus, the quantity 1.6667 x 10-3 could be written as 1.6667D-3. The exponent itself can be either positive or negative, but it must be a whole number, i.e., it cannot contain a decimal point.
Several Visual Basic numeric constants are shown below:
0 -5280
1 -5028E+3
+1 1492
0.1E+1 3000000
10E-1 3D+6
String Constants A string constant is a sequence of characters (i.e., letters, numbers and certain special characters, such as +, -, /, *, =, $, etc.), enclosed in quotation marks. Blank spaces can be included within a string. A quotation mark can also be placed within a string, but it must be written as two adjacent quotation marks. String constants are used to represent nonnumeric information, such as names, addresses, etc. There is no practical restriction on the maximum number of characters that can be included within a string constant. Thus, the maximum length of a string constant can be considered infinite. Several string constants are shown below:
“SANTA CLAUS” “Please type a value for C:” “$19.95” “Welcome to the 21st Century” “X1 = “ “3730425” “The answer is ” “Do you wish to try again?” “The professor said, “”Please don’t snore in class”” “
Data Types Visual Basic supports all common data types, including Integer, Long (i.e., long integer), Single, Double, and String. The language also supports other data types, such as Boolean, Byte, Currency, and Date data, as well as Variant-type and user-defined data types. Below is a specific description of each data type in Visual Basic. Boolean - indicates the presence of logical data that can contain either of two values, True or False. Example:
Dim myVariable As Boolean myVariable = True Information and Communication Technology Department Palompon Institute of Technology
15
VISUAL BASIC FUNDAMENTALS
2
Byte – the smallest data type allowed by Visual Basic and are stored as single, unsigned, 8-bit (1byte) numbers ranging in value from 0 – 255. Only positive numbers can be held in a Byte data type. Currency - provides a special numeric format to store monetary values. Currency data types always include four decimal digits. This data type is useful for calculations involving money and for fixed-point calculations in which accuracy is particularly important. Date - contains a specially formatted number that represents the date or time with the range from 1 January 100 to 31 December 9999 for dates and 0:00:00 to 23:59:59 for times. Double - stores a double precision floating point number with a range from -1.79769313486232E308 to -4.94065645841247E-324 for Negative values, and 1.79769313486232E308 to 4.94065645841247E-324 for Positive values. Integer - a whole number that ranges from -32,768 to 32,767. Integer variables were probably the most used type of variables. Long - a signed integer stored in four bytes of memory ranging from -2,147,483,648 to 2,147,486,647. Object – Visual Basic uses object variables to store and refer to objects. Here are a few examples:
Dim frm As Form Dim txtDisplay as TextBox Private Sub Form_Activate() Set frm = Form1 Set txtDisplay = Text1 frm.Caption = “Created from Objects” txtDisplay.text = “I am also created from Objects” End Sub Single - a single precision number that represents fractional numbers, numbers with decimal places, or exponential numbers. Negative values are ranging from -3.402823E38 to -1.401298E-45, with Positive values ranging from 1.401298E-45 to 3.402823E38. String - can contain up to approximately 2 billion of characters. User-Defined Type – a user-defined type is a compound structure that holds different variables of simpler data types. Before you can use a User-Defined Type variable, you must first define its structure, using a Type statement in the declaration section of a module. For example:
Private Type EmployeeUDT empName As String empDepartID As Long End Type Once you have defined a Type structure, you can create variables of that type as you would do with any Visual Basic data type. You can then access its individual items using the dot syntax:
Dim Emp as EmpolyeeUDT Emp.Name = “John Smith” Emp.DepartmentID = 6988 Variant – variant is the default data type for Visual Basic. In other words, if you use a variable without specifying its type, as in the following line of code: Information and Communication Technology Department Palompon Institute of Technology
16
VISUAL BASIC FUNDAMENTALS
2
Dim myVariable this will become a Variant variable. Decimal – a floating-point data type with a higher precision than Double, but it has a smaller range value. Decimal is a singular case among the data types supported by Visual Basic in that you can’t explicitly declare a variable using As Decimal. Instead, you assign a value to a Variant variable using the CDec conversion function, for example:
Dim SUM As Variant SUM = CDec(txtInput.Text)
Type Conversion Visual Basic also supports conversion from one data type to another. Some conversion functions supported by Visual Basic are: Function
Description
CBool(variable_name)
Converts a variable to a Boolean data type.
CByte(variable_name)
Converts a variable to a Byte data type.
CDec(variable_name)
Converts a variable to a Decimal data subtype. This conversion function provides the only method of creating a Decimal data subtype.
CDate(variable_name)
Converts a variable to a Date/Time data type.
CCur(variable_name)
Converts a variable to a Currency data type.
CDbl(variable_name)
Converts a variable to a Double precision data type. The function accepts any number within the limits of the Double data type or any string data that can be converted to a number within the range of the double data type.
CInt(variable_name)
Converts a variable to an Integer data type. CInt accepts any number within the limits of the integer data type or any string data that can be converted to a number and is within the limits of the integer data type.
CLng(variable_name)
Converts a variable to a Long data type. The function accepts any number within the limits of the long integer data type or any string data that can be converted to a number whose value lies within the range of a long integer.
CSng(variable_name)
Converts a variable to a Single data type. The function accepts any number within the limits of the single data type or any string data that can be converted to a number within the range of the Single data type.
CStr(variable_name)
Converts a variable to a String data type. CStr accepts any kind of data.
CVar(variable_name)
Converts a variable to a Variant data type. CVar accepts any kind of data.
Information and Communication Technology Department Palompon Institute of Technology
17
VISUAL BASIC FUNDAMENTALS
2
Variables A variable is a name that represents a numerical quantity, a string, or some other basic data item (e.g., a date, true/false condition, etc.). The following rules apply to the naming of variables: 1.
2. 3. 4.
A variable name must begin with a letter. Additional characters may be letters or digits. Certain other characters may also be included, though the period and special data-typing characters (e.g., %, &, !, #, and $) are not permitted. In general, it is good programming practice to avoid the use of characters other than letters and digits. A variable name cannot exceed 255 characters. As a practical matter, however, variable names rarely approach this size. Visual Basic does not distinguish between uppercase and lowercase letters. Many programmers use uppercase letters as word separators within a single variable name (e.g., FreezingPoint, TaxRate, etc.). Visual Basic includes a number of reserved words (e.g., Dim, If, Else, Select, Case, Do, etc.). These reserved words represent commands, function names, etc. They cannot be used as variable names.
Some examples of variable names are:
Area Counter
Radius CustomerName
X xmax C4 Account_Number UnpaidBalance
Variable Declaration You declare variable in Visual Basic by using the following form:
Dim variable_name As DataType In this syntax, • Dim is the keyword that tells Visual Basic that you want to declare a variable. • variable_name is the name of the variable. • As is the keyword that tells Visual Basic that you’re defining the data type for the variable. • DataType is the data type of the variable. Several variable declarations are shown below:
Dim Dim Dim Dim
age As Integer Area As Single FirstName As String StudentName As String * 30
If you have a number of variables to declare, you can do this on a single line by separating them with commas, as in the following Dim statement:
Dim TaxRate As Single, Income As Double, Dependents As Integer
Information and Communication Technology Department Palompon Institute of Technology
18
VISUAL BASIC FUNDAMENTALS
2
Constant Declaration To declare a constant in Visual Basic, you have to use the Const statement and assign or set its value. After a constant is declared, it cannot be modified or assigned a new value. You can declare a constant within a procedure or at the top of a module, in the declarations section. Modulelevel constants are private by default. To declare a public module-level constant, precede the Const statement with the Public keyword. You can explicitly declare a private constant by preceding the Const statement with the Private keyword to make it easier to read and interpret your code. The following example declares the Public constant conAge as an Integer and assigns it the value 34.
Public Const conAge As Integer = 34 You can declare one or more constants in a single statement. To specify a data type, you must include the data type for each constant. In the following statement, the constants conAge and conWage are declared as Integer and Currency, respectively.
Const conAge As Integer = 34, conWage As Currency = 3500
Making Explicit Declaration In Visual Basic, you can implicitly declare a variable by simply using it in an assignment statement, as in the following example:
Private Sub Form_Activate() displayThisSTRING = “HELLO WORLD” Print displayThisSTRING End Sub All variables that are implicitly declared are of type Variant. Variables of type Variant require more memory resources than most other variables. Your application will be more efficient if you declare variables explicitly and with a specific data type. Explicitly declaring all variables reduces the incidence of name-conflict and spelling mistakes. Using the Option Explicit statement is good programming practice. It forces us to declare all variables and constants. You can automatically have Visual Basic add this to new modules as they are created by checking the Require Variable Declaration option, which can be found on the Editor tab of the Options dialog (Select Tools >> Options). You can also used explicit declaration by placing the statement Option Explicit in a module before any procedure. When the Option Explicit statement is used, Visual Basic can determine variables you used in your program that has not been declared.
Information and Communication Technology Department Palompon Institute of Technology
19
VISUAL BASIC FUNDAMENTALS
2
Suffixes Rather than declaring a data type explicitly (using Dim or Const statement), a variable or named constant can be associated with a data type by adding a single-character suffix to the end of the variable/constant name. several of the more commonly used suffixes are listed below. Suffix % & ! # $
Data Type
integer long integer single double string
Shown below are several variables whose data types are defined by suffixes. Variable
Data Type
Index% Counter& TaxRate! Ratio# CustomerName$
integer long integer Single double string
The use of suffixes is derived from earlier versions of the Basic language, and is included in Visual Basic largely for purposes of consistency and backward compatibility. Modern programming practice encourages the use of explicit data type declarations rather than suffixes.
Scope and Lifetime of Variables Sometimes you need a variable to be seen by all the procedures within your project, while other variables should only be available within a particular procedure. The visibility of a variable is known as its scope. Closely related to a variable’s scope is its lifetime, or the period of program execution when the variable is live and available for use. Precisely where you declare a variable or constant in a program determines its scope and its lifetime. Global Variables In Visual Basic jargon, global variables are those variables declared using the Public keyword in the declaration section of Visual Basic modules. Conceptually, these variables are the simplest of the group because they survive for the life of the application and their scope is the entire application. Module-Level Variables A variable has module-level scope when it can be accessed by all the subroutines and functions contained in a particular module. Module-level variables are visible only from within the module they belong to and can’t be accessed from the outside. To create a variable with module-level scope, you must declare it in the module’s declaration section (that is to say, outside of any subroutine or function) by using either the Dim or Private Statement. Procedure-Level Scope A variable that is declared within an individual procedure (that is, within a subroutine or a function) can only be used within that procedure, and is therefore said to have procedure-level scope. The lifetime of a procedure-level variable ends when the End Sub or End Function statement is executed. Information and Communication Technology Department Palompon Institute of Technology
20
VISUAL BASIC FUNDAMENTALS
2
There is also a special type of variable that has procedure-level scope, called a static variable. A static variable is defined within a procedure, and although it has procedure-level scope, it has module-level lifetime. In practice, this means that you can only use the variable within the procedure in which it’s defined, but its value is maintained between calls to the procedure. To declare a static variable, you use the Static keyword in a procedure, for example:
Static lngExecuted As Long Declaring a variable within a procedure must be done using the Dim or Static statement; you can’t declare a variable or constant as Public or Private within a procedure.
Visual Basic Operators Special symbols, called arithmetic operators, are used to indicate arithmetic operations such as addition, subtraction, multiplication, division, and exponentiation. These operators are used to connect numeric constants and numeric variables, thus forming arithmetic expressions. Visual Basic Arithmetic Operators Visual Basic Operator
Description
Visual Basic Expression ( x=9, y=4, z=9.5 )
+
Addition
x+y = 13
-
Subtraction
x-y = 5
*
Multiplication
x*y = 36
/
Division (float)
z/y = 2.375
\
Division (integer)
z\y = 2
^
Exponentiation
x^y = 6561
-
Negation
-y = -4
Mod
Modulus
x Mod y = 1
Order of Precedence Operator(s)
Operation(s)
Order of Evaluation (precedence)
( )
Parentheses
Evaluated first. If the parentheses are nested, the expression in the innermost part is evaluated first. If there is one or more pairs of parentheses on the same level (i.e. not nested), they are evaluated left to right.
^
Exponentiation
Evaluated second. If there is one or more of this operator on the same level, they are evaluated left to right.
-
Negation
Evaluated third. If there is one or more of this operator on the same level, they are evaluated left to right.
Information and Communication Technology Department Palompon Institute of Technology
21
VISUAL BASIC FUNDAMENTALS
2
* or /
Multiplication and/or Floating-point Division
Evaluated fourth. If there is one or more of this operator on the same level, they are evaluated left to right.
\
Division (integer)
Evaluated fifth. If there is one or more of this operator on the same level, they are evaluated left to right.
Mod
Modulus
Evaluated sixth. If there is one or more of this operator on the same level, they are evaluated left to right.
+ or -
Addition and/or Subtraction
Evaluated last. If there is one or more of this operator on the same level, they are evaluated left to right.
The following example shows how operators are evaluated in Visual Basic using the order of precedence table given above. Example 1:
z
=
p
*
r
Mod
1
q
3
+
w
4
/
x
–
y
5
2
Example 2:
y
=
( a
* 1
x
+ 2
b )
Mod 5
( b
/
5 )
3
Information and Communication Technology Department Palompon Institute of Technology
* 4
u
-
2
6
22