Вы находитесь на странице: 1из 33

Basic Programming Fundamentals

Variable

A location in the computer's memory where data is stored. You can change the contents of a
variable but its name and storage area are reserved for use until you end the Visual Basic
session or release the variable. Variables have a name (the word you use to refer), a data type
(which determines the kind of data the variable can store) and value (to the value that variable
contains).

Scalar Variables and Array Variables


A variable containing a single value is a scalar variable. A variable that can contain more than
one related value to a single variable. This is called an array variable.

Variable Category
Category Name Description
Public/Global Variables declared using the Public Statement are visible to all procedures in
all modules in all applications. not just the ones they are defined in.
Private/Local A variable that is accessible only within a function or procedure. Other
procedures or functions cannot access this variable's data.

Variable Lifetime
A term for a variable that continues to exist after a function call or program is finished. Public
and static variables continue to exist, local variables do not.

Scope of Variables
The range of reference for an object or variable . For example, local variables can be
referenced only within the procedure they were defined. Public variables are accessible from
anywhere in the application.

Scope Private Public

Procedure-level Variables are private to the procedure in Not applicable. You cannot
which they appear. declare public variables within a
procedure.

Module-level Variables are private to the module in which Variables are available to all
they appear. modules.
Basic Programming Fundamentals

Visual Basic Data Types

Visual Basic classifies the information mentioned above into two major data types, they are the
numeric data types and the non-numeric data types.

Numeric Data Types


Numeric data types are types of data that consist of numbers, which can be computed
mathematically with various standard operators. Examples of numeric data types are
examination marks, height, weight, the number of students in a class and etc.

Type Storage Range of Values


Byte 1 byte 0 to 255
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,648
Single 4 bytes -3.402823E+38 to -1.401298E-45 for negative values
1.401298E-45 to 3.402823E+38 for positive values.
Double 8 bytes -1.79769313486232e+308 to -4.94065645841247E-324 for negative values
4.94065645841247E-324 to 1.79769313486232e+308 for positive values.
Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807

Non-numeric Data Types


Nonnumeric data types are data that cannot be manipulated mathematically using standard
arithmetic operators.

Data Type Storage Range


String(fixed length) Length of string 1 to 65,400 characters
String(variable length) Length + 10 bytes 0 to 2 billion characters
Date 8 bytes January 1, 100 to December 31, 9999
Boolean 2 bytes True or False
Object 4 bytes Any embedded object
Variant(numeric) 16 bytes Any value as large as Double
Variant(text) Length+22 bytes Same as variable-length string

Variable Declaration
Declaring a variable means giving it a name, a data type and sometimes an initial value. The
declaration can be explicit or implicit.
Implicit Declaration

In implicit Variable declaration do not need to define variable type.Visual Basic adjust its
type according to the value you assign to it.Visual Basic use by default variable type is
variant.
Basic Programming Fundamentals
Explicit Declaration

In Explicit Variable declaration you must define variable type.

Variable naming Conventions:


• Must begin with an alphabetic character.
• Can't contain an embedded period or type-declaration character.
• Must be unique within the same scope.
• Must be no longer than 255 characters
Declaring Variables
Identifier variablename [As type]

Identifier Description
Dim Variables declared with Dim at the module level are available to all procedures
within the module. At the procedure level, variables are available only within the
procedure.
Private Private variables are available only to the module in which they are declared.
Public Variables declared using the Public statement are available to all procedures in all
modules in all applications
Global are available to all applications but Define in Module Level
Static Variables declared with the Static statement retain their values as long as the code
is running.

Example
Dim bA As Byte
Dim bolA As Boolean
Dim iA,iB,iC As Integer
Dim lA As Long
Dim sA As Single
Dim dA As Double
Dim daA As Date
Dim oA As Object
Dim strA As String
Dim strfA As String * 20, Dim vA As Variant 'Depend on Value
Static stA As Integer

Assigning Values to Variables


After declaring various variables using the Identifier, we can assign values to those variables.
The general format of an assignment is
Variable=Expression
Example
bolA=True
iA =100 : lA =100.35
strfA =”Karachi,Pakistan”
Basic Programming Fundamentals
Converting Data Types
Visual Basic provides several conversion functions you can use to convert values into a specific
data type. To convert a value to Currency, for example, you use the CCur function:
PayPerWeek = CCur(hours * hourlyPay)

Conversion function Converts an expression to


Cbool Boolean
Cbyte Byte
Ccur Currency
Cdate Date
CDbl Double
Cint Integer
CLng Long
CSng Single
CStr String
Cvar Variant

Constants

A constant is a meaningful name that takes the place of a number or string that does not
change. you can't modify a constant or assign a new value to it as you can to a variable. There
are two sources for constants:
• Intrinsic or system-defined constants are provided by applications and controls. Visual
Basic constants are listed in the Visual Basic (VB) and Visual Basic
• Symbolic or user-defined constants are declared using the Const statement

Creating Your Own Constants


The syntax for declaring a constant is:
[Public|Private] Const constantname [As type] = expression

Scoping User-Defined Constants


A Const statement has scope like a variable declaration, and the same rules apply:
Example
Const conPi = 3.14159265358979
Public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #01/01/2010#
Public Const conVersion = "01.01.A"
Const conCodeName = "Vista"
Basic Programming Fundamentals

Operators in Visual Basic

To compute inputs from users and to generate results, we need to use various mathematical
operators. In Visual Basic

Arithmetic and Text Operators


Operator Definition Example Result
^ Exponent (power of) 4^2 16
* Multiply 5*4 20
/ Divide 20 / 4 5
+ Add 3+4 7
- Subtract 7-3 4
Mod Remainder of division 20 Mod 6 2
\ Integer division 20 \ 6 3
& String concatenation "Karachi," & " " & "Pakistan" "Karachi, Pakistan"
Example
Dim number1, number2 AS Integer
Private sub Command1_Click
number1=val(Text1.Text) : number2=val(Text2.Text)
Label1.Caption= number1 ^ number2
Label2.Caption= number1 * number2 : Label3.Caption= number1 / number2
Label4.Caption= number1 + number2 : Label5.Caption= number1 - number2
Label6.Caption= number1 Mod number2
Label7.Caption= number1 \ number2
Label8.Caption= Text1.Text & “ “ & Text2.Text
End Sub

Conditional Operators
To control the VB program flow, we can use various conditional operators. Basically, they
resemble mathematical operators. Conditional operators are very powerful tools, they let the
VB program compare data values and then decide what action to take

Conditional Operators
Operator Definition Example Result
= Equal to 9 = 11 False
> Greater than 11 > 9 True
< Less than 11 < 9 False
>= Greater or equal 15 >= 15 True
<= Less or equal 9 <= 15 True
<> Not equal 9 <> 9 False
Basic Programming Fundamentals

Logical Operators
An operator that produces a logical result (true or false); sometimes called a Boolean operator.
Logical Operators
Operator Meaning Example Result
And Both sides must be true (9 = 9) AND (7 = False
6)
or One side or other must be true (9 = 9) OR (7 = 6) True
Xor One side or other must be true but not
both
Not Negates truth Not (9=9) False

Introduction to Control Structures

Control structures allow you to control the flow of your program's execution. If left unchecked
by control-flow statements, a program's logic will flow through statements from left to right, and
top to bottom.

Decision Structures
Visual Basic procedures can test conditions and then, depending on the results of that test,
perform different operations.

• If...Then
• If...Then...Else
• Select Case
If...Then
Use an If...Then structure to execute one or more statements conditionally. You can use either a
single-line syntax or a multiple-line block syntax:

Single-line Syntax
If condition Then statement

Multiple-line block Syntax


If condition1 Then
[statementblock-1]
[ElseIf condition2 Then
[statementblock-2]] ...
[Else
[statementblock-n]]
End If
The condition is usually a comparison, but it can be any expression that evaluates to a numeric
value. Visual Basic interprets this value as True or False; a zero numeric value is False, and any
nonzero numeric value is considered True. If condition is True, Visual Basic executes all the
statements following the Then keyword.
Basic Programming Fundamentals

IF...Then Examples
Private Sub cmdIF1_Click() Private Sub cmdIF3_Click()
a = 16 Dim number, digits As Integer
If a > 10 Then a = a + 1: Print a Dim myString As String
End Sub
number = InputBox("Please enter any
Private Sub cmdIF2_Click()
number.")
Dim number, digits As Integer
Dim myString As String
If number = "" Then Exit Sub
number = 53
If number < 10 Then
myString = "One"
If number < 10 Then
ElseIf number >= 10 And number < 100 Then
digits = 1
myString = "Two"
Else
ElseIf number >= 100 And number < 1000
digits = 2
Then
End If
myString = "Three"
Else
If digits = 1 Then myString = "One digit"
myString = "Un-Know"
Else myString = "More than one digits"
End If
Print myString
End Sub
If myString = "Un-Know" Then
Print myString & " number"
Else
Print "You press " & myString & " digit
number"
End If
End Sub
Private Sub cmdIF4_Click()
Dim Percantage As Byte
Cls
frmIF.FontSize = 15
frmIF.BackColor = &H8000000F
Percantage = InputBox("Enter your percantage to know grade.", "Grade Information")
If Percantage >= 80 And Percantage <= 100 Then
frmIF.BackColor = vbGreen
Print "Your Grade is A+"
Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 70 And Percantage < 80 Then
frmIF.BackColor = vbBlue
Print "Your Grade is A"
Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 60 And Percantage < 70 Then
frmIF.BackColor = vbYellow
Print "Your Grade is B"
Print "Percantage is " & Percantage & "%"
Basic Programming Fundamentals
ElseIf Percantage >= 50 And Percantage < 60 Then
frmIF.BackColor = &H8000000D
Print "Your Grade is C"
Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 40 And Percantage < 50 Then
frmIF.BackColor = &H80FF&
Print "Your Grade is D"
Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 30 And Percantage < 40 Then
frmIF.BackColor = &H40C0&
Print "Your Grade is E"
Print "Percantage is " & Percantage & "%"
Else
frmIF.BackColor = vbRed
Print "Your Grade is Fail"
Print "Percantage is " & Percantage & "%"
End If
End Sub

Select Case
A Select Case structure works with a single test expression that is evaluated once, at the top of
the structure. Visual Basic then compares the result of this expression with the values for each
Case in the structure. If there is a match, it executes the block of statements associated with
that Case:

Syntax
Select Case testexpression
[Case expressionlist1
[statementblock-1]]
[Case expressionlist2
[statementblock-2]]
..
[Case Else
[statementblock-n]]
End Select

Example
Private Sub cmdSC1_Click() Private Sub cmdSC2_Click()
Grade = InputBox("Enter your Grade.") age = InputBox("Enter your age")
Select Case UCase(Grade) Select Case age
Case "A" Case 18
MsgBox "Excellent" MsgBox "OOP! you young."
Case "B" Case 35
MsgBox "Good" MsgBox "Sorry!you are not young."
Case Else End Select
MsgBox "Need Work Hard" End Sub
End Select
Basic Programming Fundamentals
End Sub

Private Sub cmdSC3_Click() Private Sub cmdSC4_Click()


Dim mark As Single Dim mark As Single
mark = CSng(InputBox("Enter your mark = CSng(InputBox("Enter your
percentage")) percentage"))
Select Case mark Select Case mark
Case Is >= 85 Case 0 To 49
MsgBox "Excellence" MsgBox "Need to work harder"
Case Is >= 70 Case 50 To 59
MsgBox "Good" MsgBox "Average"
Case Is >= 60 Case 60 To 69
MsgBox "Above Average" MsgBox "Above Average"
Case Is >= 50 Case 70 To 84
MsgBox "Average" MsgBox "Good"
Case Else Case Else
MsgBox "Need to work harder" MsgBox "Excellence"
End Select End Select
End Sub End Sub

Loop Structures

Loop structures allow you to execute one or more lines of code repetitively. The loop
structures that Visual Basic supports include:

• Do...Loop
• While …. Wend
• For...Next
• For Each...Next
Basic Programming Fundamentals
Do...Loop
Use a Do loop to execute a block of statements an indefinite number of times. There are
several variations of the Do...Loop statement.

Loop zero or more Loop at least once Description


times

Do Until condition Do In the following Do...Until loop, the


statements statements statements execute as long as the condition
Loop Loop Until condition is False

Do While condition Do In the following Do...While loop, the


statements statements statements execute as long as the condition
Loop Loop While is True
condition

Do...Until Examples
Private Sub cmdDoUntil1_Click() Private Sub cmdDoUntil2_Click()
'Natural Number 'Odd Number
Dim x As Integer Dim x As Integer
Cls Cls
x=1 x=1
Do Until x > 20 Do Until x > 20
Print x Print x
x=x+1 x=x+2
Loop Loop
End Sub End Sub
Private Sub cmdDoUntil3_Click() Private Sub cmdDoUntil4_Click()
'Even Number 'Table of 2
Dim x As Integer Dim x As Integer
Cls Cls
x=2 x=1
Do Until x > 20 Do Until x > 10
Print x Print "2 X" & x & "=" & 2 * x
x=x+2 x=x+1
Loop Loop
End Sub End Sub
Private Sub cmdDoUntil5_Click() Private Sub cmdDoUntil6_Click()
'Get Table Number From User 'Get Screen Font List
tbl = InputBox("Enter table number which Dim x As Integer
you want to generate.", "Get Table Number") Cls
If tbl = "" Then Exit Sub x = Screen.FontCount
Cls Do Until x = -1
x=1 Print Screen.Fonts(x)
Do Until x > 10 x=x-1
Print tbl & "X" & x & "=" & tbl * x Loop
x=x+1 End Sub
Basic Programming Fundamentals
Loop
End Sub
Private Sub cmdDoUntil7_Click()
Dim x, y, z As Integer
'Nested Loop
Cls
Print "X"; Space(5); "Y"; Space(5); "Z"
Print "--------------------------"
x=1
Do Until x > 3
y=1
Do Until y > 3
z=1
Do Until z > 3
Print x; Space(5); y; Space(5); z
z=z+1
Loop
y=y+1
Loop
x=x+1
Loop
End Sub

Loop...Until Examples
Private Sub cmdLoopUntil1_Click() Private Sub cmdLoopUntil2_Click()
'Natural Number 'Odd Number
Dim x As Integer Dim x As Integer
Cls Cls
x=1 x=1
Do Do
Print x Print x
x=x+1 x=x+2
Loop Until x > 20 Loop Until x > 20
End Sub End Sub
Private Sub cmdLoopUntil3_Click() Private Sub cmdLoopUntil4_Click()
'Even Number 'Table of 2
Dim x As Integer Dim x As Integer
Cls Cls
x=2 x=1
Do Do
Print x Print "2 X" & x & "=" & 2 * x
x=x+2 x=x+1
Loop Until x > 20 Loop Until x > 10
End Sub End Sub
Private Sub cmdLoopUntil5_Click() Private Sub cmdLoopUntil6_Click()
'Get Table Number From User 'Get Screen Font List
Basic Programming Fundamentals
tbl = InputBox("Enter table number which Dim x As Integer
you want to generate.", "Get Table Number") Cls
If tbl = "" Then Exit Sub x = Screen.FontCount
Cls Do
x=1 Print Screen.Fonts(x)
Do x=x-1
Print tbl & "X" & x & "=" & tbl * x Loop Until x = -1
x=x+1 End Sub
Loop Until x > 10
End Sub
Private Sub cmdLoopUntil7_Click()
Dim x, y, z As Integer
'Nested Loop
Cls
Print "X"; Space(5); "Y"; Space(5); "Z"
Print "--------------------------"
x=1
Do
y=1
Do
z=1
Do
Print x; Space(5); y; Space(5); z
z=z+1
Loop Until z > 3
y=y+1
Loop Until y > 3
x=x+1
Loop Until x > 3
End Sub

Do...While Examples
Private Sub cmdDoWhile1_Click() Private Sub cmdDoWhile2_Click()
'Natural Number 'Odd Number
Dim x As Integer Dim x As Integer
Cls Cls
x=1 x=1
Do While x <= 20 Do While x <= 20
Print x Print x
x=x+1 x=x+2
Loop Loop
End Sub End Sub
Private Sub cmdDoWhile3_Click() Private Sub cmdDoWhile4_Click()
'Even Number 'Table of 2
Dim x As Integer Dim x As Integer
Cls Cls
Basic Programming Fundamentals
x=2 x=1
Do While x <= 20 Do While x <= 10
Print x Print "2 X" & x & "=" & 2 * x
x=x+2 x=x+1
Loop Loop
End Sub End Sub
Private Sub cmdDoWhile5_Click() Private Sub cmdDoWhile6_Click()
'Get Table Number From User 'Get Screen Font List
tbl = InputBox("Enter table number which Dim x As Integer
you want to generate.", "Get Table Number") Cls
If tbl = "" Then Exit Sub x = Screen.FontCount
Cls Do While x <> 0
x=1 Print Screen.Fonts(x)
Do While x <= 10 x=x-1
Print tbl & "X" & x & "=" & tbl * x Loop
x=x+1 End Sub
Loop
End Sub
Private Sub cmdDoWhile7_Click()
Dim x, y, z As Integer
'Nested Loop
Cls
Print "X"; Space(5); "Y"; Space(5); "Z"
Print "--------------------------"
x=1
Do While x <= 3
y=1
Do While y <= 3
z=1
Do While z <= 3
Print x; Space(5); y; Space(5); z
z=z+1
Loop
y=y+1
Loop
x=x+1
Loop
End Sub

Loop...While Examples
Private Sub cmdLoopWhile1_Click() Private Sub cmdLoopWhile2_Click()
'Natural Number 'Odd Number
Dim x As Integer : Cls : x = 1 Dim x As Integer : Cls : x = 1
Do Do
Print x Print x
x=x+1 x=x+2
Basic Programming Fundamentals
Loop While x <= 20 Loop While x <= 20
End Sub End Sub
Private Sub cmdLoopWhile3_Click() Private Sub cmdLoopWhile4_Click()
'Even Number 'Table of 2
Dim x As Integer Dim x As Integer
Cls Cls
x=2 x=1
Do Do
Print x Print "2 X" & x & "=" & 2 * x
x=x+2 x=x+1
Loop While x <= 20 Loop While x <= 10
End Sub End Sub
Private Sub cmdLoopWhile5_Click() Private Sub cmdLoopWhile6_Click()
'Get Table Number From User 'Get Screen Font List
tbl = InputBox("Enter table number which Dim x As Integer
you want to generate.", "Get Table Number") Cls
If tbl = "" Then Exit Sub x = Screen.FontCount
Cls Do
x=1 Print Screen.Fonts(x)
Do x=x-1
Print tbl & "X" & x & "=" & tbl * x Loop While x <> 0
x=x+1 End Sub
Loop While x <= 10
End Sub
Private Sub cmdLoopWhile7_Click()
Dim x, y, z As Integer
'Nested Loop
Cls
Print "X"; Space(5); "Y"; Space(5); "Z"
Print "--------------------------"
x=1
Do
y=1
Do
z=1
Do
Print x; Space(5); y; Space(5); z
z=z+1
Loop While z <= 3
y=y+1
Loop While y <= 3
x=x+1
Loop While x <= 3
End Sub
Basic Programming Fundamentals

While ….. Wend Examples


Private Sub cmdWhileWend1_Click() Private Sub cmdWhileWend2_Click()
'Natural Number 'Odd Number
Dim x As Integer Dim x As Integer
Cls Cls
x=1 x=1
While x <= 20 While x <= 20
Print x Print x
x=x+1 x=x+2
Wend Wend
End Sub End Sub
Private Sub cmdWhileWend3_Click() Private Sub cmdWhileWend4_Click()
'Even Number 'Table of 2
Dim x As Integer Dim x As Integer
Cls Cls
x=2 x=1
While x <= 20 While x <= 10
Print x Print "2 X" & x & "=" & 2 * x
x=x+2 x=x+1
Wend Wend
End Sub End Sub
Private Sub cmdWhileWend5_Click() Private Sub cmdWhileWend6_Click()
'Get Table Number From User 'Get Screen Font List
tbl = InputBox("Enter table number which Dim x As Integer
you want to generate.", "Get Table Number") Cls
If tbl = "" Then Exit Sub x = Screen.FontCount
Cls While x <> 0
x=1 Print Screen.Fonts(x)
While x <= 10 x=x-1
Print tbl & "X" & x & "=" & tbl * x Wend
x=x+1 End Sub
Wend
End Sub
Private Sub cmdWhileWend7_Click()
Dim x, y, z As Integer
'Nested Loop
Cls
Print "--------------------------"
Print "X"; Space(5); "Y"; Space(5); "Z"
Print "--------------------------"
x=1
While x <= 3
y=1
While y <= 3
z=1
Basic Programming Fundamentals
While z <= 3
Print x; Space(5); y; Space(5); z
z=z+1
Wend
y=y+1
Wend
x=x+1
Wend
End Sub

For...Next
When you know you must execute the statements a specific number of times, however, a For…
Next loop is a better choice. Unlike a Do loop, a For loop uses a variable called a counter that
increases or decreases in value during each repetition of the loop. The syntax is:
For counter = start To end [Step increment]
statements
Next [counter]

For ….. Next Examples


Private Sub cmdFN1_Click() Private Sub cmdFN2_Click()
'Natural Number 'Odd Number
Cls Cls
For x = 1 To 20 For x = 1 To 20 Step 2
Print x Print Tab(5); x
Next x Next
End Sub End Sub
Private Sub cmdFN3_Click() Private Sub cmdFN4_Click()
'Even Number 'Generate Table of 2
Cls Cls
For x = 2 To 20 Step 2 For x = 1 To 10
Print Tab(10); x Print "2 X " & x & "=" & 2 * x
Next x Next x
End Sub End Sub
Private Sub cmdFN5_Click() Private Sub cmdFN6_Click()
'Get Table Number From User 'Get Screen Font List
tbl = InputBox("Enter table number which Cls
you want to generate.", "Get Table Number") For x = 1 To Screen.FontCount - 1
If tbl = "" Then Exit Sub Print Screen.Fonts(x)
Cls Next x
For x = 1 To 10 End Sub
Print tbl & " X " & x & " = " & tbl * x
Next x
End Sub

Private Sub cmdFN7_Click()


Basic Programming Fundamentals
'Nested For Loop
Cls
Print "X"; Space(5); "Y"; Space(5); "Z"
Print "--------------------------"
For x = 1 To 3
For y = 1 To 3
For z = 1 To 3
Print x; Space(5); y; Space(5); z
Next z
Next y
Next x
End Sub

For … Each
A For Each...Next loop is similar to a For...Next loop, but it repeats a group of statements for
each element in a collection of objects or in an array instead of repeating the statements a
specified number of times. This is especially helpful if you don't know how many elements are in a
collection.
For Each element In group
statements
Next element

For ….. Each Examples


Private Sub cmdFE1_Click()
For Each ctl In frmIF.Controls
If TypeOf ctl Is TextBox Then
ctl.BackColor = vbYellow
End If
Next ctl
End Sub

Exiting a Control Structure


The Exit statement allows you to exit directly from a Loop, Procedure, or Function procedure.

Exit Sub Exit From Procedure


Exit Function Exit From Function
Exit For Exit From For … Next Loop
Exit Do Exit From Do … While Loop
Basic Programming Fundamentals
Introduction to Procedures

You can simplify programming tasks by breaking programs into smaller logical components. These
components called procedures
There are two major benefits of programming with procedures:
• Procedures allow you to break your programs into discrete logical units, each of which
you can debug more easily than an entire program without procedures.
• Procedures used in one program can act as building blocks for other programs, usually
with little or no modification.

Procedures Type
General Procedures
A general procedure tells the application how to perform a specific task. Once a
general procedure is defined, it must be specifically invoked by the application.
Event Procedures
When an object in Visual Basic recognizes that an event has occurred, it
automatically invokes the event procedure using the name corresponding to the event.
The syntax for a Sub procedure is:
[Private|Public][Static]Sub procedurename (arguments)
statements
End Sub

Calling Procedures
A procedure differs from a Function procedure in that a Sub procedure cannot be called by
using its name within an expression. A call to a Sub is a stand-alone statement. Also, a Sub does
not return a value in its name as does a function. However, like a Function, a Sub can modify the
values of any variables passed to it.
There are two ways to call a Sub procedure:
' Both of these statements call a Sub named MyProc.
Call MyProc (FirstArgument, SecondArgument)
MyProc FirstArgument, SecondArgument
Note that when you use the Call syntax, arguments must be enclosed in parentheses. If you
omit the Call keyword, you must also omit the parentheses around the arguments.

Passing Arguments to Procedures


This information consists of variables passed to the procedure when it is called. When a
variable is passed to a procedure, it is called an argument.

Argument Data Types


The arguments for procedures you write have the Variant data type by default. However, you
can declare other data types for arguments.
ProcedureName (argumentName [AS type])
Basic Programming Fundamentals
Example:
‘Declare Procedure ‘Declare Procedure
Private Sub Welcome() Public Sub ApplicationTitle(frm As Object)
Print frm.Caption = "Inventory System " & Now
"--------------------------------------------" End Sub
Print "Wellcome to Visual Basic 6"
Print
"--------------------------------------------"
End Sub
‘Calling Procedure ‘Calling Procedure
Private Sub cmdPro1_Click() Private Sub cmdPro2_Click()
Call Welcome Call ApplicationTitle(frmProcedure)
End Sub End Sub

Passing Arguments By Value


Only a copy of a variable is passed when an argument is passed by value. If the procedure
changes the value, the change affects only the copy and not the variable itself. Use the ByVal
keyword to indicate an argument passed by value.
ProcedureName (ByVal argumentName [AS type])
Passing Arguments By Reference
Passing arguments by reference gives the procedure access to the actual variable contents in
its memory address location. As a result, the variable's value can be permanently changed by
the procedure to which it is passed. Passing by reference is the default in Visual Basic.
ProcedureName (ByRef argumentName [AS type])
Using Optional Arguments
You can specify arguments to a procedure as optional by placing the Optional keyword in the
argument list. If you specify an optional argument, all subsequent arguments in the argument
list must also be optional and declared with the Optional keyword.
ProcedureName (Optional ByVal argumentName [AS type])
Providing a Default for an Optional Argument
It's also possible to specify a default value for an optional argument.
ProcedureName (Optional ByVal argumentName AS type=Value)
Using an Indefinite Number of Arguments
Generally, the number of arguments in the procedure call must be the same as in the procedure
specification. Using the ParamArray keyword allows you to specify that a procedure will accept
an arbitrary number of arguments. This allows you to write functions like Sum:
ProcedureName (ParamArray argumentName( ))
Creating Simpler Statements with Named Arguments
For many built-in functions, statements, and methods, Visual Basic provides the option of using
named arguments as a shortcut for typing argument values. With named arguments, you can
provide any or all of the arguments, in any order, by assigning a value to the named argument.
You do this by typing the argument name plus a colon followed by an equal sign and the value
Basic Programming Fundamentals
(MyArgument:= "SomeValue") and placing that assignment in any sequence delimited by
commas. This is especially useful if your procedures have several optional arguments that you do
not always need to specify.
Example:
‘Declare With ByVal and Optional argument ‘Declare With ByRef and Providing default
Private Sub Power(ByVal x As Integer, value
Optional ByVal y) Private Sub StringProcedure(ByRef pString As
If IsMissing(y) Then String, ByRef a As Integer, Optional ByVal b As
y=1 Integer = 1)
End If pString = "After Calling String"
Print (x ^ y) a = 100
End Sub b = 200
End Sub
‘Calling Procedure ‘Calling Procedure
Private Sub cmdPro3_Click() Private Sub cmdPro4_Click()
Call Power(2) Dim mystring As String, x As Integer, y As
End Sub Integer
‘Declare With ParamArray mystring = "StartString"
Private Sub sum(ParamArray intsum()) x = 10: y = 20
For Each x In intsum Print "Before Calling Procedure": Print
y=y+x Print mystring
Next Print x: Print y
Print y Print "----------------------------"
End Sub Print "After Calling Procedure": Print
‘Calling Procedure StringProcedure mystring, x, y
Private Sub cmdPro5_Click() Print mystring
Call sum(1, 2, 3, 4, 5) Print x: Print y
End Sub End Sub

‘Declare Procedure ‘Calling With Named argument


Private Sub Total(ByVal x As Integer, Optional Private Sub cmdPro6_Click()
ByVal y As Integer = 0, Optional ByVal z As Call Total(10)
Integer = 0) Call Total(x:=10, z:=25)
Print x + y + z End Sub
End Sub

Introduction to Function Procedures

Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr. In addition, you can use
the Function statement to write your own Function procedures.
The syntax for a Function procedure is:
[Private|Public][Static]Function procedurename (arguments) [As type]
statements
End Function
Basic Programming Fundamentals
There are three differences between Sub and Function procedures:
• Generally, you call a function by including the function procedure name and arguments on
the right side of a larger statement or expression (returnvalue = function()).
• Function procedures have data types, just as variables do. This determines the type of
the return value. (In the absence of an As clause, the type is the default Variant type.)
• You return a value by assigning it to the procedurename itself. When the Function
procedure returns a value, this value can then become part of a larger expression.
• Function return value but sub procedure don’t return any value

Calling Function Procedures


Usually, you call a function procedure you've written yourself the same way you call an intrinsic
Visual Basic function like Abs; that is, by using its name in an expression:
' All of the following statements would call a function
Print 10 * FunctionName
X = FunctionName
If FunctionName = 10 Then Debug.Print "Out of Range"
X = AnotherFunction(10 * FunctionName)
Example:
'Function take no argument and no return 'Function take argument and return value
any value Private Function Sum0(x As Integer, y As
Private Function ClearScreen() Integer) As Double
Cls Sum0 = x + y
For Each ctl In frmFunction.Controls End Function
If TypeOf ctl Is TextBox Then 'Function take argument and return value
ctl.Text = "" With Optional argument
End If Private Function Sum1(a As Integer, b As
Next ctl Integer, Optional c As Integer, Optional d As
End Function Integer) As Double
Sum1 = a + b + c + d
End Function
Private Sub cmdFun1_Click() 'Function take argument and return value
Call ClearScreen With Optional argument and assign default
End Sub value
Private Function Sum2(x As Integer, y As
Integer, Optional z As Integer = 1) As Double
Sum2 = x + y + z
End Function
Private Sub cmdFun2_Click() Private Sub cmdFun2_Click()
MsgBox Sum0(100, 50) MsgBox Sum1(50, 50, 60)
MsgBox Sum2(10, 20) MsgBox Sum1(a:=10, b:=20, d:=15)
End Sub End Sub
'Function take argument and return value 'Function take argument and return value
Public Function Min(ByVal x As Double, ByVal y Public Function Max(ByVal x As Double, ByVal y
As Double) As Double As Double) As Double
If x > y Then If x > y Then
Min = y Max = x
Basic Programming Fundamentals
Else Else
Min = x Max = y
End If End If
End Function End Function

Function take argument but no return any 'Function take argument but no return any
value using ByVal value using ByRef
Private Function FunByVal(ByVal x As Integer) Private Function FunByRef(ByRef x As Integer)
x=x+5 x=x+5
End Function End Function
Private Sub cmdFun5_Click() Private Sub cmdFun4_Click()
Dim v1 As Integer Dim v1 As Integer
v1 = 30 v1 = 30
Print v1 Print v1
Call FunByVal(v1) Call FunByRef(v1)
Print v1 Print v1
End Sub End Sub

Calling Sub Procedures/Function Procedures in Other Modules


Public procedures in other modules can be called from anywhere in the project. You might need
to specify the module that contains the procedure you're calling. The techniques for doing this
vary, depending on whether the procedure is located in a form, class, or standard module.

Sub Procedures/Function Procedures in Forms


All calls from outside the form module must point to the form module containing the procedure.
If a procedure named SomeSub is in a form module called Form1, then you can call the
procedure in Form1 by using this statement:
Call Form1.SomeSub(arguments)
Sub Procedures/Function Procedures in Class Modules
Like calling a procedure in a form, calling a procedure in a class module requires that the call to
the procedure be qualified with a variable that points to an instance of the class. For example,
DemoClass is an instance of a class named Class1:
Dim DemoClass as New Class1
DemoClass.SomeSub
Sub Procedures/Function Procedures in Standard Modules
If a procedure name is unique, you don't need to include the module name in the call. A call from
inside or outside the module will refer to that unique procedure. A procedure is unique if it
appears only in one place.If two or more modules contain a procedure with the same name, you
may need to qualify it with the module name. A call to a common procedure from the same
module runs the procedure in that module. For example, with a procedure named CommonName
in Module1 and Module2, a call to CommonName from Module2 will run the CommonName
procedure in Module2, not the CommonName procedure in Module1.A call to a common procedure
name from another module must specify the intended module. For example, if you want to call
the CommonName procedure in Module2 from Module1, use:
Module2.CommonName(arguments)
Basic Programming Fundamentals
Basic Programming Fundamentals
Introduction to Arrays

An array is a list of variables, all with the same data type and name. When we work with a single
item, we only need to use one variable. However, if we have a list of items which are of similar
type to use array. Arrays have both upper and lower bounds, and the elements of the array are
contiguous within those bounds. Because Visual Basic allocates space for each index number,
avoid declaring an array larger than necessary.
In Visual Basic there are two types of arrays:
• A fixed-size array which always remains the same size.
• A dynamic array whose size can change at run-time.
The format for declaring an array is:
Dim|Public|Private ArrayName([Subscript], [Subscript], [Subscript]) [As DataType]

- Dim, Public, and Private declare the array and its scope.
- ArrayName is the name of the array.
- Subscript is the dimensions of the array.
- DataType is any valid data type.

Declaring Fixed-Size Arrays


The general format to declare a one/Single dimensional array is as follow:
Dim|Public|Private arrayName(Subscript) as dataType
The general format to declare a Multidimensional /two dimensional array is as follow:
Dim|Public|Private ArrayName(Subscript, Subscript) as dataType
The general format to declare a Multidimensional /three dimensional array is as follow:
Dim|Public|Private ArrayName(Subscript, Subscript, Subscript) as dataType
Example of Single /One dimensional array

Private Sub cmdArray1_Click() Private Sub cmdArray2_Click()


'Declare Array 'Declare Array
Dim StudentName(4) As String Dim StudentName(1 To 5) As String
'Assign Data to Array Element 'Assign Data to Array Element
StudentName(0) = "Arshed Khan" StudentName(1) = "Arshed Khan"
StudentName(1) = "Amir Khan" StudentName(2) = "Amir Khan"
StudentName(2) = "Ahmed Ansari" StudentName(3) = "Ahmed Ansari"
StudentName(3) = "Gulzar Ahmed" StudentName(4) = "Gulzar Ahmed"
StudentName(4) = "Mohammad Ali" StudentName(5) = "Mohammad Ali"
'Access Array Element 'Access Array Element
Print StudentName(0) Print StudentName(1)
Print StudentName(1) Print StudentName(2)
Print StudentName(2) Print StudentName(3)
Print StudentName(3) Print StudentName(4)
Print StudentName(4) Print StudentName(5)
End Sub End Sub
Basic Programming Fundamentals
Private Sub cmdArray3_Click() Private Sub cmdArray4_Click()
'Declare Array 'Declare Array
Dim StudentName(4) As String Dim StudentName(1 To 5) As String
'Assign Data to Array Element 'Assign Data to Array Element
For x = 0 To 4 For x = 1 To 5
StudentName(x) = InputBox("Enter StudentName(x) = InputBox("Enter
Student Name.") Student Name.")
Next x Next x
'Access Array Element 'Access Array Element
For x = 0 To 4 For x = 1 To 5
Print StudentName(x) Print StudentName(x)
Next x Next x
End Sub End Sub

Example of Multidimensional / Two dimensional array

Private Sub cmdArray5_Click() Private Sub cmdArray6_Click()


'Declare Array 'Declare Array
Dim StudentName(3, 1) As String Dim StudentName(3, 1) As String
'Assign Data to Array Element 'Assign Data to Array Element
StudentName(0, 0) = "1001" For x = 0 To 3
StudentName(0, 1) = "Arshed Khan" For y = 0 To 1
StudentName(1, 0) = "1002" If y = 0 Then
StudentName(1, 1) = "Amir Khan" StudentName(x, y) = InputBox("Enter
StudentName(2, 0) = "1003" Student Code:")
StudentName(2, 1) = "Ahmed Ansari" Else
StudentName(3, 0) = "1004" StudentName(x, y) = InputBox("Enter
StudentName(3, 1) = "Gulzar Ahmed" Student Name:")
'Access Array Element End If
Print "Code " & "Name " Next y
Print "------------------------" Next x
Print StudentName(0, 0) & " " & 'Access Array Element
StudentName(0, 1) Print "Code " & "Name "
Print StudentName(1, 0) & " " & Print "------------------------"
StudentName(1, 1) For x = 0 To 3
Print StudentName(2, 0) & " " & Print StudentName(x, 0) & " " &
StudentName(2, 1) StudentName(x, 1)
Print StudentName(3, 0) & " " & Next x
StudentName(3, 1) End Sub
End Sub
Basic Programming Fundamentals

Example of Multidimensional / Three dimensional array

Private Sub cmdArray7_Click()


'Declare Array
Dim StudentName(1 To 2, 1 To 4, 1 To 3) As String
'Assign Data to Array Element
StudentName(1, 1, 1) = "9-A"
StudentName(1, 1, 2) = "1001"
StudentName(1, 1, 3) = "Arshed Khan"
StudentName(1, 2, 1) = "9-A"
StudentName(1, 2, 2) = "1002"
StudentName(1, 2, 3) = "Amir Khan"
StudentName(1, 3, 1) = "9-A"
StudentName(1, 3, 2) = "1003"
StudentName(1, 3, 3) = "Ahmed Ansari"
StudentName(1, 4, 1) = "9-A"
StudentName(1, 4, 2) = "1004"
StudentName(1, 4, 3) = "Gulzar Ahmed"
StudentName(2, 1, 1) = "9-B"
StudentName(2, 1, 2) = "1001"
StudentName(2, 1, 3) = "SANA"
StudentName(2, 2, 1) = "9-B"
StudentName(2, 2, 2) = "1002"
StudentName(2, 2, 3) = "HINA"
StudentName(2, 3, 1) = "9-B"
StudentName(2, 3, 2) = "1003"
StudentName(2, 3, 3) = "HUMA"
StudentName(2, 4, 1) = "9-B"
StudentName(2, 4, 2) = "1004"
StudentName(2, 4, 3) = "RABIA"
'Access Array Element
Print "Class " & "Code " & "Name "
Print "-----------------------------------------"
Print StudentName(1, 1, 1) & " " & StudentName(1, 1, 2) & " " & StudentName(1, 1, 3)
Print StudentName(1, 2, 1) & " " & StudentName(1, 2, 2) & " " & StudentName(1, 2, 3)
Print StudentName(1, 3, 1) & " " & StudentName(1, 3, 2) & " " & StudentName(1, 3, 3)
Print StudentName(1, 4, 1) & " " & StudentName(1, 4, 2) & " " & StudentName(1, 4, 3)
Print "-----------------------------------------"
Print StudentName(2, 1, 1) & " " & StudentName(2, 1, 2) & " " & StudentName(2, 1, 3)
Print StudentName(2, 2, 1) & " " & StudentName(2, 2, 2) & " " & StudentName(2, 2, 3)
Print StudentName(2, 3, 1) & " " & StudentName(2, 3, 2) & " " & StudentName(2, 3, 3)
Print StudentName(2, 4, 1) & " " & StudentName(2, 4, 2) & " " & StudentName(2, 4, 3)
End Sub
Basic Programming Fundamentals
Private Sub cmdArray8_Click()
'Declare Array
Dim StudentName(1 To 2, 1 To 4, 1 To 3) As String
'Assign Data to Array Element
For x = 1 To 2
For y = 1 To 4
For z = 1 To 3
If z = 1 Then
StudentName(x, y, z) = InputBox("Enter Student Class:")
ElseIf z = 2 Then
StudentName(x, y, z) = InputBox("Enter Student Code:")
Else
StudentName(x, y, z) = InputBox("Enter Student Name:")
End If
Next z
Next y
Next x
'Access Array Element
For x = 1 To 2
Print "Class " & "Code " & "Name "
Print "-----------------------------------------"
For y = 1 To 4
Print StudentName(x, y, 1) & " " & StudentName(x, y, 2) & " " & StudentName(x, y, 3)
Next y
Next x
End Sub
Basic Programming Fundamentals

Example of Array of arrays

Private Sub cmdArray9_Click() Private Sub cmdArray10_Click()


'Declare Array Dim StudentName As Variant
Dim StudentName9ACode(1 To 3) As Integer Dim sName
Dim StudentName9AName(1 To 3) As String StudentName = Array("Arshed", "Ali",
Dim Class9(1 To 2) As Variant "Amir", "Gulzar")
'Assign Data to Array Element For x = 0 To 3
For x = 1 To 3 Print StudentName(x)
StudentName9ACode(x) = InputBox("Enter Next x
Student Code:") End Sub
StudentName9AName(x) = Private Sub cmdArray11_Click()
InputBox("Enter Student Name:") Dim Serial(4) As String
Next x If IsArray(Serial) Then
Class9(1) = StudentName9ACode() For x = LBound(Serial) To UBound(Serial)
Class9(2) = StudentName9AName() Serial(x) = x
'Access Array Element Next x
Print "Code " & "Name " End If
Print "----------------" If IsArray(Serial) Then
For x = LBound(StudentName9ACode) To For x = LBound(Serial) To UBound(Serial)
UBound(StudentName9ACode) Print Serial(x)
Print Class9(1)(x) & " " & Class9(2)(x) Next x
Next x Print "Your array have been erased."
End Sub Erase Serial
End If
End Sub

IsArray Test the variable type


Array Used to assign multiple values in one statement
Option Base Set the default lower index limit
LBound | UBound Determine the upper and lower bounds of the specified
dimension
Erase Clear the array's contents
Redim Change the size of the array at runtime
Preserve optional keyword that forces Visual Basic to retain all existing
elements' values
Dim | Private | Public | Static Declare the array
Basic Programming Fundamentals

Declaring Dynamic Arrays


The ReDim statement is used to size or resize a dynamic array that has already been formally
declared using a Private, Public, or Dim statement with empty parentheses (without dimension
subscripts).
The ReDim keyword's syntax is:
ReDim [Preserve] ArrayName(Subscript) As DataType
- ReDim is the keyword that denotes we are redimensioning an array.
- Preserve is an optional keyword that forces Visual Basic to retain all existing
elements' values. If you use the Preserve keyword, you can resize only the last array
dimension and you can't change the number of dimensions at all.
Example of Dynamic Array

Private Sub cmdArray12_Click()


Dim StudentName() As String
NofStudent = InputBox("How many Student in your class?")
ReDim StudentName(Val(NofStudent))
For x = 0 To UBound(StudentName)
StudentName(x) = InputBox("Enter Student Name")
Next x
For x = 0 To UBound(StudentName)
Print StudentName(x)
Next x
End Sub
Private Sub cmdArray13_Click() Private Sub cmdArray14_Click()
Dim StudentName() As String Dim strStudentNames() As String
ReDim StudentName(1, 1) As String Dim strText As String
StudentName(0, 0) = "1001" Dim blDimensioned As Boolean
StudentName(0, 1) = "Ali" Dim lngPosition As Long
StudentName(1, 0) = "1002" Do
StudentName(1, 1) = "Arshed" strText = InputBox("Enter a Student name:")
Print StudentName(0, 0) & " " & If strText <> "" Then
StudentName(0, 1) If blDimensioned = True Then
Print StudentName(1, 0) & " " & 'Yes, so extend the array one element large
StudentName(1, 1) than its current upper bound.
ReDim Preserve StudentName(1, 0 ReDim Preserve strStudentNames(0 To
To UBound(StudentName) + 1) As UBound(strStudentNames) + 1) As String
String Else
StudentName(1, 0) = "1001" 'No, so dimension it and flag it as
StudentName(1, 1) = "Ali" dimensioned.
StudentName(1, 2) = "Class 9A" ReDim strStudentNames(0 To 0) As String
:Print blDimensioned = True
Print StudentName(0, 0) & " " & End If
StudentName(0, 1) 'Add the Student Name to the last element in
Print StudentName(1, 0) & " " & the array.
StudentName(1, 1) & " " & strStudentNames(UBound(strStudentNames)) =
Basic Programming Fundamentals
StudentName(1, 2) strText
ReDim StudentName(2, 1) As String End If
StudentName(0, 0) = "1001" Loop Until strText = ""
StudentName(0, 1) = "Ali" 'Display entered Student names:
StudentName(1, 0) = "1002" For lngPosition = LBound(strStudentNames) To
StudentName(1, 1) = "Arshed" UBound(strStudentNames)
StudentName(2, 0) = "1003" Print strStudentNames(lngPosition)
StudentName(2, 1) = "Gulzar" :Print Next lngPosition
Print StudentName(0, 0) & " " & 'Erase array
StudentName(0, 1) Erase strStudentNames
Print StudentName(1, 0) & " " & End Sub
StudentName(1, 1)
Print StudentName(2, 0) & " " &
StudentName(2, 1)
End Sub

User-Defined Data Types

Variables of different data types when combined as a single variable to hold several related
informations is called a User-Defined data type.A Type statement is used to define a user-
defined type in the General declaration section of a form or module. User-defined data types
can only be private in form while in standard modules can be public or private.The Type
definition is basically a "template" on which other variables are defined; the template itself
does not store any data. To use a UDT, you must define a variable
The syntax for defining a UDT is:

[Public | Private] Type TypeName


Variable1 As datatype
...
Variablen As datatype
End Type
The following rules apply to UDTs:
• UDTs declared only at the module-level (Do not declare a UDT in an individual Sub or
Function)
• UDTs may have Public (project-level) or Private (module-level) scope. The default is
Public.
• UDTs with Public scope may only be defined in standard modules, not forms.
Example

Private Type EmpName Private Sub cmdType1_Click()


FirstName As String Dim empRec As EmpRecord
LastName As String empRec.empCode = "1001"
End Type empRec.EmpName.FirstName = "Ahmed"
empRec.EmpName.LastName = "Ali"
Private Type EmpRecord empRec.empSalary = 2500
empCode As Integer Print "Employee Code :" & empRec.empCode
Basic Programming Fundamentals
EmpName As EmpName Print "Employee Name :" &
empSalary As Currency empRec.EmpName.FirstName & " " &
SalaryMonth(12) As String empRec.EmpName.LastName
End Type Print "Employee Salary :" & empRec.empSalary
End Sub
‘UDT with Array
Private Sub cmdType2_Click()
Dim EmpRec(4) As EmpRecord
For x = 0 To 4
EmpRec(x).EmpCode = InputBox("Enter Code")
EmpRec(x).EmpName.FirstName = InputBox("Enter Name")
EmpRec(x).EmpSalary = InputBox("Enter Salary")
EmpRec(x).SalaryMonth(1) = "Jan"
Next x
For x = 0 To 4
Print EmpRec(x).EmpCode & " " & EmpRec(x).EmpName.FirstName & " " &
EmpRec(x).EmpSalary & " " & EmpRec(x).SalaryMonth(1)
Next x
End Sub

Example UDT With Sub Procedure and Function Procedure


‘Structure ‘Call Procedure and Function
Private Type InventoryItem Private Sub cmdType3_Click()
Item_Code As String Dim item As InventoryItem
Item_Name As String item.Item_Code = "1001"
Item_Desc As String item.Item_Name = "Pen (Pointer)"
Item_Price As Double item.Item_Desc = "Pen use for dark writing"
Item_Qty As Integer item.Item_Price = 18
End Type item.Item_Qty = 36
‘Procedure
Private Sub Itemlist(itemRec As 'Call Procedure and pass parameter
InventoryItem) Call Itemlist(item)
Debug.Print "Item Code " & "Item Name " &
"Item Description " & "Qty " & "Price " & 'Call Function and get parameter
"Amount" Print "Item Code " & getItemlist().Item_Code
Debug.Print itemRec.Item_Code & " " & Print "Item Name " &
itemRec.Item_Name & " " & getItemlist().Item_Name
itemRec.Item_Desc & " " & Print "Item Description " &
itemRec.Item_Price & " " & itemRec.Item_Qty getItemlist.Item_Desc
& " " & itemRec.Item_Qty * Print "Item Qty " & getItemlist.Item_Qty
itemRec.Item_Price Print "Item Price " & getItemlist.Item_Price
End Sub Print "Total Amount " &
‘Function getItemlist().Item_Qty *
Private Function getItemlist() As getItemlist().Item_Price
InventoryItem End Sub
Dim item As InventoryItem
Basic Programming Fundamentals
item.Item_Code = "1002"
item.Item_Name = "Book 1 (English Poem)"
item.Item_Desc = "Book for class 1"
item.Item_Price = 57
item.Item_Qty = 50
getItemlist = item
End Function

Enums (enumerations)

Enums (enumerations) are structures you define when you need a set of constant values. An
Enum must be declared outside of any Sub Procedure and Function body. The elements of the
Enum type are initialized to constant values within the Enum statement. The assigned values
can't be modified at run time and can include both positive and negative numbers. the first
constant in an enumeration is initialized to the value 0, and subsequent constants are initialized
to the value of one more that the previous constant.
Syntax
[Public | Private] Enum name
membername [= constantexpression]
membername [= constantexpression]
. . .
End Enum
Example

Private Enum DaysName Private Sub cmdEnum_Click()


Monday = 1 Print DaysName.Friday
Tuesday = 2 Print CalculateHourTime(Sunday)
Wednesday = 3 End Sub
Thursday = 4 Private Function CalculateHourTime(day As
Friday = 5 DaysName)
Saturday = 6 If day = Sunday Then
Sunday = 7 Print "No any Hour Time allow on Sunday."
End Enum Else
Print "Calculation of Hour Time"
End If
End Function
Basic Programming Fundamentals

Collection

A collection is a way of grouping a set of related items. Collections are used in Visual Basic to
keep track of many things, such as the loaded forms in your program (the Forms collection), or
all the controls on a form (the Controls collection).Visual Basic provides the generic Collection
class to give you the ability to define your own collections. You can create as many Collection
objects — that is, instances of the Collection class. Each Collection object comes with
properties and methods you can use to insert, delete, and retrieve the items in the collection.

Property or method Description


Add method Add items to the collection.
Count property Return the number of items in the collection. Read-only.
Item method Return an item, by index or by key.
Remove method Delete an item from the collection, by index or by key.

Example

Private Sub cmdCollection1_Click() ‘Control Collection


'Create object variable for collection Private Sub cmdCollection2_Click()
Dim itm As New Collection For Each ctl In frmCollection.Controls
'Add value in collection If TypeOf ctl Is TextBox Then
itm.Add ("A") ctl.Text = ""
itm.Add ("B") End If
itm.Add ("c") Next ctl
itm.Add ("d") End Sub
'Count number of item in collection
Print itm.Count
'Retrive item from collection
Print itm.item(2)
Print itm(3)
'Remove item from collection
itm.Remove (2)
Print itm.Count
End Sub

Вам также может понравиться