Post on 09-Apr-2018
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 1/33
Basic Programming Fundamentals
Variable
A location in the computer's memory where data is stored. You can change the contents of avariable but its name and storage area are reserved for use until you end the Visual Basicsession 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 thanone 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 inall 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. Otherprocedures or functions cannot access this variable's data.
Variable LifetimeA term for a variable that continues to exist after a function call or program is finished. Publicand 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 bereferenced only within the procedure they were defined. Public variables are accessible fromanywhere in the application.
Scope Private Public
Procedure-level Variables are private to the procedure inwhich they appear.
Not applicable. You cannotdeclare public variables within aprocedure.
Module-level Variables are private to the module in which
they appear.
Variables are available to all
modules.
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 2/33
Basic Programming Fundamentals
Visual Basic Data Types
Visual Basic classifies the information mentioned above into two major data types, they are thenumeric 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 computedmathematically with various standard operators. Examples of numeric data types areexamination 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 standardarithmetic 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 DeclarationDeclaring a variable means giving it a name, a data type and sometimes an initial value. Thedeclaration can be explicit or implicit.
Implicit Declaration
In implicit Variable declaration do not need to define variable type.Visual Basic adjust itstype according to the value you assign to it.Visual Basic use by default variable type isvariant.
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 3/33
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 theprocedure.
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 allmodules 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 codeis running.
Example Dim bA As ByteDim bolA As BooleanDim iA,iB,iC As IntegerDim lA As LongDim sA As SingleDim dA As DoubleDim daA As DateDim oA As ObjectDim strA As String
Dim strfA As String * 20, Dim vA As Variant 'Depend on ValueStatic 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=ExpressionExample
bolA=TrueiA =100 : lA =100.35
strfA =”Karachi,Pakistan”
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 4/33
Basic Programming Fundamentals
Converting Data Types
Visual Basic provides several conversion functions you can use to convert values into a specificdata 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 BooleanCbyte Byte
Ccur Currency
Cdate Date
CDbl Double
Cint Integer
CLng Long
CSng Single
CStr StringCvar Variant
Constants
A constant is a meaningful name that takes the place of a number or string that does notchange. you can't modify a constant or assign a new value to it as you can to a variable. Thereare two sources for constants:
• Intrinsic or system-defined constants are provided by applications and controls. VisualBasic 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 ConstantsThe syntax for declaring a constant is:
[Public|Private] Const constantname [As type] = expression
Scoping User-Defined ConstantsA Const statement has scope like a variable declaration, and the same rules apply:
ExampleConst conPi = 3.14159265358979Public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #01/01/2010#Public Const conVersion = "01.01.A"Const conCodeName = "Vista"
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 5/33
Basic Programming Fundamentals
Operators in Visual Basic
To compute inputs from users and to generate results, we need to use various mathematicaloperators. 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 \ number2Label8.Caption= Text1.Text & “ “ & Text2.Text
End Sub
Conditional Operators
To control the VB program flow, we can use various conditional operators. Basically, theyresemble mathematical operators. Conditional operators are very powerful tools, they let theVB 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
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 6/33
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 =6) False
or One side or other must be true (9 = 9) OR (7 = 6) True
Xor One side or other must be true but notboth
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, andtop 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...ThenUse an If...Then structure to execute one or more statements conditionally. You can use either asingle-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 IfThe 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 anynonzero numeric value is considered True. If condition is True, Visual Basic executes all thestatements following the Then keyword.
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 7/33
Basic Programming Fundamentals
IF ...Then Examples
Private Sub cmdIF1_Click()a = 16If a > 10 Then a = a + 1: Print a
End Sub
Private Sub cmdIF3_Click()Dim number, digits As IntegerDim myString As String
number = InputBox("Please enter any
number.")
If number = "" Then Exit Sub
If number < 10 ThenmyString = "One"
ElseIf number >= 10 And number < 100 ThenmyString = "Two"
ElseIf number >= 100 And number < 1000
Then myString = "Three"Else
myString = "Un-Know"End If
If myString = "Un-Know" Then
Print myString & " number"Else
Print "You press " & myString & " digit
number"End IfEnd Sub
Private Sub cmdIF2_Click()Dim number, digits As IntegerDim myString As String
number = 53
If number < 10 Then
digits = 1Else
digits = 2
End If
If digits = 1 Then myString = "One digit"Else myString = "More than one digits"
Print myStringEnd Sub
Private Sub cmdIF4_Click()Dim Percantage As ByteClsfrmIF.FontSize = 15frmIF.BackColor = &H8000000FPercantage = InputBox("Enter your percantage to know grade.", "Grade Information")If Percantage >= 80 And Percantage <= 100 Then
frmIF.BackColor = vbGreenPrint "Your Grade is A+"Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 70 And Percantage < 80 ThenfrmIF.BackColor = vbBluePrint "Your Grade is A"Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 60 And Percantage < 70 ThenfrmIF.BackColor = vbYellowPrint "Your Grade is B"
Print "Percantage is " & Percantage & "%"
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 8/33
Basic Programming Fundamentals
ElseIf Percantage >= 50 And Percantage < 60 ThenfrmIF.BackColor = &H8000000DPrint "Your Grade is C"Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 40 And Percantage < 50 ThenfrmIF.BackColor = &H80FF&
Print "Your Grade is D"Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 30 And Percantage < 40 ThenfrmIF.BackColor = &H40C0&Print "Your Grade is E"Print "Percantage is " & Percantage & "%"
ElsefrmIF.BackColor = vbRedPrint "Your Grade is Fail"Print "Percantage is " & Percantage & "%"
End IfEnd Sub
Select Case
A Select Case structure works with a single test expression that is evaluated once, at the top ofthe structure. Visual Basic then compares the result of this expression with the values for eachCase in the structure. If there is a match, it executes the block of statements associated withthat Case:
Syntax
Select Case testexpression[Case expressionlist1[statementblock-1]]
[Case expressionlist2[statementblock-2]]..
[Case Else[statementblock-n]]
End Select
Example
Private Sub cmdSC1_Click()Grade = InputBox("Enter your Grade.")Select Case UCase(Grade)
Case "A"MsgBox "Excellent"
Case "B"MsgBox "Good"
Case ElseMsgBox "Need Work Hard"
End Select
Private Sub cmdSC2_Click()age = InputBox("Enter your age")Select Case age
Case 18MsgBox "OOP! you young."
Case 35MsgBox "Sorry!you are not young."
End SelectEnd Sub
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 9/33
Basic Programming Fundamentals
End Sub
Private Sub cmdSC3_Click()Dim mark As Singlemark = CSng(InputBox("Enter your
percentage"))
Select Case markCase Is >= 85
MsgBox "Excellence"Case Is >= 70
MsgBox "Good"Case Is >= 60
MsgBox "Above Average"Case Is >= 50
MsgBox "Average"Case Else
MsgBox "Need to work harder"End Select
End Sub
Private Sub cmdSC4_Click()Dim mark As Singlemark = CSng(InputBox("Enter your
percentage"))
Select Case markCase 0 To 49
MsgBox "Need to work harder"Case 50 To 59
MsgBox "Average"Case 60 To 69
MsgBox "Above Average"Case 70 To 84
MsgBox "Good"Case Else
MsgBox "Excellence"End Select
End Sub
Loop Structures
Loop structures allow you to execute one or more lines of code repetitively. The loopstructures that Visual Basic supports include:
• Do...Loop•
While …. Wend• For...Next• For Each...Next
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 10/33
Basic Programming Fundamentals
Do...LoopUse a Do loop to execute a block of statements an indefinite number of times. There areseveral variations of the Do...Loop statement.
Loop zero or moretimes
Loop at least once Description
Do Until condition statements
Loop
Do statements
Loop Until condition
In the following Do...Until loop, thestatements execute as long as the condition is False
Do While condition
statements
Loop
Do statements
Loop Whilecondition
In the following Do...While loop, the
statements execute as long as the condition is True
Do...Until Examples
Private Sub cmdDoUntil1_Click()'Natural NumberDim x As IntegerClsx = 1Do Until x > 20
Print xx = x + 1
LoopEnd Sub
Private Sub cmdDoUntil2_Click()'Odd NumberDim x As IntegerClsx = 1Do Until x > 20
Print xx = x + 2
LoopEnd Sub
Private Sub cmdDoUntil3_Click()'Even NumberDim x As IntegerClsx = 2Do Until x > 20
Print xx = x + 2
LoopEnd Sub
Private Sub cmdDoUntil4_Click()'Table of 2Dim x As IntegerClsx = 1Do Until x > 10
Print "2 X" & x & "=" & 2 * xx = x + 1
LoopEnd Sub
Private Sub cmdDoUntil5_Click()'Get Table Number From Usertbl = InputBox("Enter table number which
you want to generate.", "Get Table Number")If tbl = "" Then Exit SubClsx = 1Do Until x > 10
Print tbl & "X" & x & "=" & tbl * x
x = x + 1
Private Sub cmdDoUntil6_Click()'Get Screen Font ListDim x As IntegerClsx = Screen.FontCountDo Until x = -1
Print Screen.Fonts(x)x = x - 1
Loop
End Sub
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 11/33
Basic Programming Fundamentals
LoopEnd Sub
Private Sub cmdDoUntil7_Click()Dim x, y, z As Integer'Nested LoopCls
Print "X"; Space(5); "Y"; Space(5); "Z"Print "--------------------------"x = 1Do Until x > 3
y = 1Do Until y > 3
z = 1Do Until z > 3
Print x; Space(5); y; Space(5); zz = z + 1
Loopy = y + 1
Loopx = x + 1
LoopEnd Sub
Loop...Until Examples
Private Sub cmdLoopUntil1_Click()'Natural Number
Dim x As IntegerClsx = 1Do
Print xx = x + 1
Loop Until x > 20End Sub
Private Sub cmdLoopUntil2_Click()'Odd Number
Dim x As IntegerClsx = 1Do
Print xx = x + 2
Loop Until x > 20End Sub
Private Sub cmdLoopUntil3_Click()'Even NumberDim x As IntegerClsx = 2Do
Print xx = x + 2
Loop Until x > 20End Sub
Private Sub cmdLoopUntil4_Click()'Table of 2Dim x As IntegerClsx = 1Do
Print "2 X" & x & "=" & 2 * xx = x + 1
Loop Until x > 10End Sub
Private Sub cmdLoopUntil5_Click()
'Get Table Number From User
Private Sub cmdLoopUntil6_Click()
'Get Screen Font List
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 12/33
Basic Programming Fundamentals
tbl = InputBox("Enter table number which you want to generate.", "Get Table Number")
If tbl = "" Then Exit SubClsx = 1Do
Print tbl & "X" & x & "=" & tbl * xx = x + 1
Loop Until x > 10End Sub
Dim x As IntegerClsx = Screen.FontCountDo
Print Screen.Fonts(x)x = x - 1
Loop Until x = -1End Sub
Private Sub cmdLoopUntil7_Click()Dim x, y, z As Integer'Nested LoopClsPrint "X"; Space(5); "Y"; Space(5); "Z"Print "--------------------------"
x = 1Do
y = 1Do
z = 1Do
Print x; Space(5); y; Space(5); zz = z + 1
Loop Until z > 3y = y + 1
Loop Until y > 3x = x + 1
Loop Until x > 3End Sub
Do...While Examples
Private Sub cmdDoWhile1_Click()'Natural NumberDim x As IntegerCls
x = 1Do While x <= 20
Print xx = x + 1
LoopEnd Sub
Private Sub cmdDoWhile2_Click()'Odd NumberDim x As IntegerCls
x = 1Do While x <= 20
Print xx = x + 2
LoopEnd Sub
Private Sub cmdDoWhile3_Click()'Even NumberDim x As IntegerCls
Private Sub cmdDoWhile4_Click()'Table of 2Dim x As IntegerCls
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 13/33
Basic Programming Fundamentals
x = 2Do While x <= 20
Print xx = x + 2
LoopEnd Sub
x = 1Do While x <= 10
Print "2 X" & x & "=" & 2 * xx = x + 1
LoopEnd Sub
Private Sub cmdDoWhile5_Click()'Get Table Number From Usertbl = InputBox("Enter table number which
you want to generate.", "Get Table Number")If tbl = "" Then Exit SubClsx = 1Do While x <= 10
Print tbl & "X" & x & "=" & tbl * xx = x + 1
LoopEnd Sub
Private Sub cmdDoWhile6_Click()'Get Screen Font ListDim x As IntegerClsx = Screen.FontCountDo While x <> 0
Print Screen.Fonts(x)x = x - 1
LoopEnd Sub
Private Sub cmdDoWhile7_Click()Dim x, y, z As Integer'Nested LoopClsPrint "X"; Space(5); "Y"; Space(5); "Z"Print "--------------------------"x = 1Do While x <= 3
y = 1Do While y <= 3
z = 1Do While z <= 3
Print x; Space(5); y; Space(5); zz = z + 1
Loopy = y + 1
Loopx = x + 1
LoopEnd Sub
Loop...While Examples
Private Sub cmdLoopWhile1_Click()'Natural NumberDim x As Integer : Cls : x = 1Do
Print xx = x + 1
Private Sub cmdLoopWhile2_Click()'Odd NumberDim x As Integer : Cls : x = 1Do
Print xx = x + 2
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 14/33
Basic Programming Fundamentals
Loop While x <= 20End Sub
Loop While x <= 20End Sub
Private Sub cmdLoopWhile3_Click()'Even NumberDim x As IntegerCls
x = 2Do
Print xx = x + 2
Loop While x <= 20End Sub
Private Sub cmdLoopWhile4_Click()'Table of 2Dim x As IntegerCls
x = 1Do
Print "2 X" & x & "=" & 2 * xx = x + 1
Loop While x <= 10End Sub
Private Sub cmdLoopWhile5_Click()'Get Table Number From Usertbl = InputBox("Enter table number which
you want to generate.", "Get Table Number")
If tbl = "" Then Exit SubClsx = 1Do
Print tbl & "X" & x & "=" & tbl * xx = x + 1
Loop While x <= 10End Sub
Private Sub cmdLoopWhile6_Click()'Get Screen Font ListDim x As IntegerCls
x = Screen.FontCountDo
Print Screen.Fonts(x)x = x - 1
Loop While x <> 0End Sub
Private Sub cmdLoopWhile7_Click()Dim x, y, z As Integer'Nested LoopClsPrint "X"; Space(5); "Y"; Space(5); "Z"Print "--------------------------"x = 1Do
y = 1Do
z = 1Do
Print x; Space(5); y; Space(5); zz = z + 1
Loop While z <= 3y = y + 1
Loop While y <= 3x = x + 1
Loop While x <= 3End Sub
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 15/33
Basic Programming Fundamentals
While ….. Wend Examples
Private Sub cmdWhileWend1_Click()'Natural NumberDim x As IntegerClsx = 1While x <= 20
Print xx = x + 1
WendEnd Sub
Private Sub cmdWhileWend2_Click()'Odd NumberDim x As IntegerClsx = 1While x <= 20
Print xx = x + 2
WendEnd Sub
Private Sub cmdWhileWend3_Click()'Even NumberDim x As IntegerCls
x = 2While x <= 20Print xx = x + 2
WendEnd Sub
Private Sub cmdWhileWend4_Click()'Table of 2Dim x As IntegerCls
x = 1While x <= 10Print "2 X" & x & "=" & 2 * xx = x + 1
WendEnd Sub
Private Sub cmdWhileWend5_Click()'Get Table Number From Usertbl = InputBox("Enter table number which
you want to generate.", "Get Table Number")
If tbl = "" Then Exit SubClsx = 1While x <= 10
Print tbl & "X" & x & "=" & tbl * xx = x + 1
WendEnd Sub
Private Sub cmdWhileWend6_Click()'Get Screen Font ListDim x As IntegerCls
x = Screen.FontCountWhile x <> 0
Print Screen.Fonts(x)x = x - 1
WendEnd Sub
Private Sub cmdWhileWend7_Click()Dim x, y, z As Integer
'Nested LoopClsPrint "--------------------------"Print "X"; Space(5); "Y"; Space(5); "Z"Print "--------------------------"x = 1While x <= 3
y = 1While y <= 3
z = 1
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 16/33
Basic Programming Fundamentals
While z <= 3Print x; Space(5); y; Space(5); zz = z + 1
Wendy = y + 1
Wend
x = x + 1Wend
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]
statementsNext [counter]
For ….. Next Examples
Private Sub cmdFN1_Click()'Natural NumberClsFor x = 1 To 20
Print xNext x
End Sub
Private Sub cmdFN2_Click()'Odd NumberClsFor x = 1 To 20 Step 2
Print Tab(5); xNext
End Sub
Private Sub cmdFN3_Click()'Even NumberClsFor x = 2 To 20 Step 2
Print Tab(10); xNext x
End Sub
Private Sub cmdFN4_Click()'Generate Table of 2ClsFor x = 1 To 10
Print "2 X " & x & "=" & 2 * xNext x
End Sub
Private Sub cmdFN5_Click()
'Get Table Number From Usertbl = InputBox("Enter table number which you want to generate.", "Get Table Number")
If tbl = "" Then Exit SubClsFor x = 1 To 10
Print tbl & " X " & x & " = " & tbl * xNext x
End Sub
Private Sub cmdFN6_Click()
'Get Screen Font ListClsFor x = 1 To Screen.FontCount - 1
Print Screen.Fonts(x)Next x
End Sub
Private Sub cmdFN7_Click()
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 17/33
Basic Programming Fundamentals
'Nested For LoopClsPrint "X"; Space(5); "Y"; Space(5); "Z"Print "--------------------------"For x = 1 To 3
For y = 1 To 3
For z = 1 To 3Print x; Space(5); y; Space(5); z
Next zNext y
Next xEnd 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 aspecified number of times. This is especially helpful if you don't know how many elements are in acollection.
For Each element In groupstatements
Next element
For ….. Each Examples
Private Sub cmdFE1_Click()For Each ctl In frmIF.Controls
If TypeOf ctl Is TextBox Thenctl.BackColor = vbYellow
End IfNext 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
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 18/33
Basic Programming Fundamentals
Introduction to Procedures
You can simplify programming tasks by breaking programs into smaller logical components. Thesecomponents called proceduresThere 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 ProceduresA general procedure tells the application how to perform a specific task. Once ageneral procedure is defined, it must be specifically invoked by the application.
Event ProceduresWhen 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 byusing its name within an expression. A call to a Sub is a stand-alone statement. Also, a Sub doesnot 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, youcan declare other data types for arguments.
ProcedureName (argumentName [AS type])
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 19/33
Basic Programming Fundamentals
Example:
‘Declare ProcedurePrivate Sub Welcome()
Print"--------------------------------------------"
Print "Wellcome to Visual Basic 6"
Print"--------------------------------------------"End Sub
‘Declare ProcedurePublic Sub ApplicationTitle(frm As Object)
frm.Caption = "Inventory System " & NowEnd Sub
‘Calling ProcedurePrivate Sub cmdPro1_Click()
Call WelcomeEnd Sub
‘Calling ProcedurePrivate Sub cmdPro2_Click()
Call ApplicationTitle(frmProcedure)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 ByValkeyword 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 inits memory address location. As a result, the variable's value can be permanently changed bythe procedure to which it is passed. Passing by reference is the default in Visual Basic.
ProcedureName (ByRef argumentName [AS type])
Using Optional ArgumentsYou can specify arguments to a procedure as optional by placing the Optional keyword in theargument list. If you specify an optional argument, all subsequent arguments in the argumentlist 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 usingnamed arguments as a shortcut for typing argument values. With named arguments, you canprovide 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
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 20/33
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 donot always need to specify.
Example:
‘Declare With ByVal and Optional argumentPrivate Sub Power(ByVal x As Integer,
Optional ByVal y)If IsMissing(y) Then
y = 1End IfPrint (x ^ y)
End Sub
‘Declare With ByRef and Providing defaultvalue
Private Sub StringProcedure(ByRef pString AsString, ByRef a As Integer, Optional ByVal b AsInteger = 1)
pString = "After Calling String"a = 100b = 200
End Sub
‘Calling ProcedurePrivate Sub cmdPro3_Click()
Call Power(2)End Sub
‘Calling ProcedurePrivate Sub cmdPro4_Click()
Dim mystring As String, x As Integer, y AsInteger
mystring = "StartString"x = 10: y = 20Print "Before Calling Procedure": PrintPrint mystringPrint x: Print yPrint "----------------------------"Print "After Calling Procedure": PrintStringProcedure mystring, x, yPrint mystringPrint x: Print y
End Sub
‘Declare With ParamArrayPrivate Sub sum(ParamArray intsum())
For Each x In intsumy = y + x
NextPrint y
End Sub
‘Calling Procedure
Private Sub cmdPro5_Click()Call sum(1, 2, 3, 4, 5)
End Sub
‘Declare ProcedurePrivate Sub Total(ByVal x As Integer, OptionalByVal y As Integer = 0, Optional ByVal z AsInteger = 0)
Print x + y + zEnd Sub
‘Calling With Named argumentPrivate Sub cmdPro6_Click()
Call Total(10)Call Total(x:=10, z:=25)
End Sub
Introduction to Function Procedures
Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr. In addition, you can usethe 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
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 21/33
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 ofthe 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 intrinsicVisual Basic function like Abs; that is, by using its name in an expression:
' All of the following statements would call a functionPrint 10 * FunctionNameX = FunctionNameIf FunctionName = 10 Then Debug.Print "Out of Range"X = AnotherFunction(10 * FunctionName)
Example:
'Function take no argument and no returnany valuePrivate Function ClearScreen()
ClsFor Each ctl In frmFunction.Controls
If TypeOf ctl Is TextBox Thenctl.Text = ""
End If
Next ctlEnd Function
'Function take argument and return valuePrivate Function Sum0(x As Integer, y AsInteger) As Double
Sum0 = x + yEnd Function
'Function take argument and return valueWith Optional argumentPrivate Function Sum1(a As Integer, b As
Integer, Optional c As Integer, Optional d AsInteger) As Double
Sum1 = a + b + c + dEnd Function
Private Sub cmdFun1_Click()Call ClearScreen
End Sub
'Function take argument and return valueWith Optional argument and assign defaultvaluePrivate Function Sum2(x As Integer, y AsInteger, Optional z As Integer = 1) As Double
Sum2 = x + y + zEnd Function
Private Sub cmdFun2_Click()MsgBox Sum0(100, 50)MsgBox Sum2(10, 20)
End Sub
Private Sub cmdFun2_Click()MsgBox Sum1(50, 50, 60)MsgBox Sum1(a:=10, b:=20, d:=15)
End Sub
'Function take argument and return value
Public Function Min(ByVal x As Double, ByVal yAs Double) As Double
If x > y Then
Min = y
'Function take argument and return value
Public Function Max(ByVal x As Double, ByVal yAs Double) As Double
If x > y Then
Max = x
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 22/33
Basic Programming Fundamentals
ElseMin = x
End IfEnd Function
ElseMax = y
End IfEnd Function
Function take argument but no return any
value using ByValPrivate Function FunByVal(ByVal x As Integer)
x = x + 5End Function
'Function take argument but no return any
value using ByRefPrivate Function FunByRef(ByRef x As Integer)
x = x + 5End Function
Private Sub cmdFun5_Click()Dim v1 As Integerv1 = 30Print v1Call FunByVal(v1)Print v1
End Sub
Private Sub cmdFun4_Click()Dim v1 As Integerv1 = 30Print v1Call FunByRef(v1)Print v1
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 needto specify the module that contains the procedure you're calling. The techniques for doing thisvary, 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 tothe 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 Class1DemoClass.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 frominside or outside the module will refer to that unique procedure. A procedure is unique if itappears only in one place.If two or more modules contain a procedure with the same name, youmay need to qualify it with the module name. A call to a common procedure from the samemodule runs the procedure in that module. For example, with a procedure named CommonNamein Module1 and Module2, a call to CommonName from Module2 will run the CommonNameprocedure in Module2, not the CommonName procedure in Module1.A call to a common procedurename from another module must specify the intended module. For example, if you want to callthe CommonName procedure in Module2 from Module1, use:
Module2.CommonName(arguments)
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 23/33
Basic Programming Fundamentals
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 24/33
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 singleitem, we only need to use one variable. However, if we have a list of items which are of similartype to use array. Arrays have both upper and lower bounds, and the elements of the array arecontiguous 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 dataTypeExample of Single /One dimensional array
Private Sub cmdArray1_Click()'Declare ArrayDim StudentName(4) As String'Assign Data to Array ElementStudentName(0) = "Arshed Khan"StudentName(1) = "Amir Khan"StudentName(2) = "Ahmed Ansari"
StudentName(3) = "Gulzar Ahmed"StudentName(4) = "Mohammad Ali"'Access Array ElementPrint StudentName(0)Print StudentName(1)Print StudentName(2)Print StudentName(3)Print StudentName(4)
End Sub
Private Sub cmdArray2_Click()'Declare ArrayDim StudentName(1 To 5) As String'Assign Data to Array ElementStudentName(1) = "Arshed Khan"StudentName(2) = "Amir Khan"StudentName(3) = "Ahmed Ansari"
StudentName(4) = "Gulzar Ahmed"StudentName(5) = "Mohammad Ali"'Access Array ElementPrint StudentName(1)Print StudentName(2)Print StudentName(3)Print StudentName(4)Print StudentName(5)
End Sub
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 25/33
Basic Programming Fundamentals
Private Sub cmdArray3_Click()'Declare ArrayDim StudentName(4) As String'Assign Data to Array ElementFor x = 0 To 4
StudentName(x) = InputBox("Enter
Student Name.")Next x'Access Array ElementFor x = 0 To 4
Print StudentName(x)Next x
End Sub
Private Sub cmdArray4_Click()'Declare ArrayDim StudentName(1 To 5) As String'Assign Data to Array ElementFor x = 1 To 5
StudentName(x) = InputBox("Enter
Student Name.")Next x'Access Array ElementFor x = 1 To 5
Print StudentName(x)Next x
End Sub
Example of Multidimensional / Two dimensional array
Private Sub cmdArray5_Click()
'Declare ArrayDim StudentName(3, 1) As String'Assign Data to Array ElementStudentName(0, 0) = "1001"StudentName(0, 1) = "Arshed Khan"StudentName(1, 0) = "1002"StudentName(1, 1) = "Amir Khan"StudentName(2, 0) = "1003"StudentName(2, 1) = "Ahmed Ansari"StudentName(3, 0) = "1004"
StudentName(3, 1) = "Gulzar Ahmed"'Access Array ElementPrint "Code " & "Name "Print "------------------------"Print StudentName(0, 0) & " " &
StudentName(0, 1)Print StudentName(1, 0) & " " &
StudentName(1, 1)Print StudentName(2, 0) & " " &
StudentName(2, 1)
Print StudentName(3, 0) & " " &StudentName(3, 1)End Sub
Private Sub cmdArray6_Click()
'Declare ArrayDim StudentName(3, 1) As String'Assign Data to Array ElementFor x = 0 To 3
For y = 0 To 1If y = 0 Then
StudentName(x, y) = InputBox("EnterStudent Code:")
ElseStudentName(x, y) = InputBox("Enter
Student Name:")End If
Next yNext x'Access Array ElementPrint "Code " & "Name "Print "------------------------"For x = 0 To 3
Print StudentName(x, 0) & " " &StudentName(x, 1)
Next xEnd Sub
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 26/33
Basic Programming Fundamentals
Example of Multidimensional / Three dimensional array
Private Sub cmdArray7_Click()'Declare ArrayDim 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 ElementPrint "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
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 27/33
Basic Programming Fundamentals
Private Sub cmdArray8_Click()'Declare ArrayDim StudentName(1 To 2, 1 To 4, 1 To 3) As String'Assign Data to Array ElementFor x = 1 To 2
For y = 1 To 4
For z = 1 To 3If 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 zNext y
Next x'Access Array ElementFor 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 xEnd Sub
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 28/33
Basic Programming Fundamentals
Example of Array of arrays
Private Sub cmdArray9_Click()'Declare ArrayDim StudentName9ACode(1 To 3) As IntegerDim StudentName9AName(1 To 3) As String
Dim Class9(1 To 2) As Variant'Assign Data to Array ElementFor x = 1 To 3
StudentName9ACode(x) = InputBox("EnterStudent Code:")
StudentName9AName(x) =InputBox("Enter Student Name:")
Next xClass9(1) = StudentName9ACode()Class9(2) = StudentName9AName()
'Access Array ElementPrint "Code " & "Name "Print "----------------"For x = LBound(StudentName9ACode) To
UBound(StudentName9ACode)Print Class9(1)(x) & " " & Class9(2)(x)
Next xEnd Sub
Private Sub cmdArray10_Click()Dim StudentName As VariantDim sNameStudentName = Array("Arshed", "Ali",
"Amir", "Gulzar")For x = 0 To 3Print StudentName(x)
Next xEnd Sub
Private Sub cmdArray11_Click()Dim Serial(4) As StringIf IsArray(Serial) Then
For x = LBound(Serial) To UBound(Serial)Serial(x) = x
Next xEnd IfIf IsArray(Serial) Then
For x = LBound(Serial) To UBound(Serial)Print Serial(x)
Next xPrint "Your array have been erased."Erase Serial
End IfEnd 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 specifieddimension
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 existingelements' values
Dim | Private | Public | Static Declare the array
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 29/33
Basic Programming Fundamentals
Declaring Dynamic Arrays
The ReDim statement is used to size or resize a dynamic array that has already been formallydeclared using a Private, Public, or Dim statement with empty parentheses (without dimensionsubscripts).
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 existingelements' values. If you use the Preserve keyword, you can resize only the last arraydimension 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 xFor x = 0 To UBound(StudentName)
Print StudentName(x)Next x
End Sub
Private Sub cmdArray13_Click()
Dim StudentName() As StringReDim StudentName(1, 1) As StringStudentName(0, 0) = "1001"StudentName(0, 1) = "Ali"StudentName(1, 0) = "1002"StudentName(1, 1) = "Arshed"Print StudentName(0, 0) & " " &
StudentName(0, 1)Print StudentName(1, 0) & " " &
StudentName(1, 1)
ReDim Preserve StudentName(1, 0To UBound(StudentName) + 1) AsString
StudentName(1, 0) = "1001"StudentName(1, 1) = "Ali"StudentName(1, 2) = "Class 9A"
:PrintPrint StudentName(0, 0) & " " &
StudentName(0, 1)Print StudentName(1, 0) & " " &
StudentName(1, 1) & " " &
Private Sub cmdArray14_Click()
Dim strStudentNames() As StringDim strText As StringDim blDimensioned As BooleanDim lngPosition As LongDo
strText = InputBox("Enter a Student name:")If strText <> "" Then
If blDimensioned = True Then'Yes, so extend the array one element large
than its current upper bound.
ReDim Preserve strStudentNames(0 ToUBound(strStudentNames) + 1) As String
Else'No, so dimension it and flag it as
dimensioned.ReDim strStudentNames(0 To 0) As StringblDimensioned = True
End If'Add the Student Name to the last element in
the array.
strStudentNames(UBound(strStudentNames)) =
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 30/33
Basic Programming Fundamentals
StudentName(1, 2)ReDim StudentName(2, 1) As StringStudentName(0, 0) = "1001"StudentName(0, 1) = "Ali"StudentName(1, 0) = "1002"StudentName(1, 1) = "Arshed"
StudentName(2, 0) = "1003"StudentName(2, 1) = "Gulzar" :PrintPrint StudentName(0, 0) & " " &
StudentName(0, 1)Print StudentName(1, 0) & " " &
StudentName(1, 1)Print StudentName(2, 0) & " " &
StudentName(2, 1)End Sub
strTextEnd If
Loop Until strText = ""'Display entered Student names:For lngPosition = LBound(strStudentNames) To
UBound(strStudentNames)
Print strStudentNames(lngPosition)Next lngPosition'Erase arrayErase strStudentNames
End Sub
User-Defined Data Types
Variables of different data types when combined as a single variable to hold several relatedinformations 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 typescan only be private in form while in standard modules can be public or private.The Typedefinition is basically a "template" on which other variables are defined; the template itselfdoes not store any data. To use a UDT, you must define a variable
The syntax for defining a UDT is:
[Public | Private] Type TypeNameVariable1 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 orFunction)
• 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 EmpNameFirstName As StringLastName As String
End Type
Private Type EmpRecord
empCode As Integer
Private Sub cmdType1_Click()Dim empRec As EmpRecordempRec.empCode = "1001"empRec.EmpName.FirstName = "Ahmed"empRec.EmpName.LastName = "Ali"empRec.empSalary = 2500
Print "Employee Code :" & empRec.empCode
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 31/33
Basic Programming Fundamentals
EmpName As EmpNameempSalary As CurrencySalaryMonth(12) As String
End Type
Print "Employee Name :" &empRec.EmpName.FirstName & " " &empRec.EmpName.LastName
Print "Employee Salary :" & empRec.empSalaryEnd Sub
‘UDT with Array
Private Sub cmdType2_Click()Dim EmpRec(4) As EmpRecordFor 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 xFor 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
‘StructurePrivate Type InventoryItem
Item_Code As StringItem_Name As StringItem_Desc As String
Item_Price As DoubleItem_Qty As Integer
End Type‘ProcedurePrivate Sub Itemlist(itemRec AsInventoryItem)
Debug.Print "Item Code " & "Item Name " &"Item Description " & "Qty " & "Price " &"Amount"
Debug.Print itemRec.Item_Code & " " &
itemRec.Item_Name & " " &itemRec.Item_Desc & " " &itemRec.Item_Price & " " & itemRec.Item_Qty& " " & itemRec.Item_Qty *itemRec.Item_PriceEnd Sub‘FunctionPrivate Function getItemlist() AsInventoryItem
Dim item As InventoryItem
‘Call Procedure and FunctionPrivate Sub cmdType3_Click()
Dim item As InventoryItemitem.Item_Code = "1001"item.Item_Name = "Pen (Pointer)"
item.Item_Desc = "Pen use for dark writing"item.Item_Price = 18item.Item_Qty = 36
'Call Procedure and pass parameterCall Itemlist(item)
'Call Function and get parameterPrint "Item Code " & getItemlist().Item_CodePrint "Item Name " &
getItemlist().Item_NamePrint "Item Description " &
getItemlist.Item_DescPrint "Item Qty " & getItemlist.Item_QtyPrint "Item Price " & getItemlist.Item_PricePrint "Total Amount " &
getItemlist().Item_Qty *getItemlist().Item_PriceEnd Sub
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 32/33
Basic Programming Fundamentals
item.Item_Code = "1002"item.Item_Name = "Book 1 (English Poem)"item.Item_Desc = "Book for class 1"item.Item_Price = 57item.Item_Qty = 50getItemlist = item
End Function
Enums (enumerations)
Enums (enumerations) are structures you define when you need a set of constant values. AnEnum must be declared outside of any Sub Procedure and Function body. The elements of theEnum type are initialized to constant values within the Enum statement. The assigned valuescan't be modified at run time and can include both positive and negative numbers. the firstconstant in an enumeration is initialized to the value 0, and subsequent constants are initializedto the value of one more that the previous constant.
Syntax
[Public | Private] Enum name
membername [= constantexpression]membername [= constantexpression]. . .
End Enum
Example
Private Enum DaysNameMonday = 1Tuesday = 2Wednesday = 3Thursday = 4Friday = 5Saturday = 6Sunday = 7
End Enum
Private Sub cmdEnum_Click()Print DaysName.FridayPrint CalculateHourTime(Sunday)
End SubPrivate Function CalculateHourTime(day AsDaysName)
If day = Sunday ThenPrint "No any Hour Time allow on Sunday."
ElsePrint "Calculation of Hour Time"
End IfEnd Function
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
http://slidepdf.com/reader/full/microsoft-visual-basic-6-basic-programming-fundamental 33/33
Basic Programming Fundamentals
Collection
A collection is a way of grouping a set of related items. Collections are used in Visual Basic tokeep track of many things, such as the loaded forms in your program (the Forms collection), orall the controls on a form (the Controls collection).Visual Basic provides the generic Collectionclass 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 withproperties 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()'Create object variable for collectionDim itm As New Collection'Add value in collectionitm.Add ("A")itm.Add ("B")itm.Add ("c")itm.Add ("d")'Count number of item in collection
Print itm.Count'Retrive item from collectionPrint itm.item(2)Print itm(3)'Remove item from collectionitm.Remove (2)Print itm.Count
End Sub
‘Control CollectionPrivate Sub cmdCollection2_Click()
For Each ctl In frmCollection.ControlsIf TypeOf ctl Is TextBox Then
ctl.Text = ""End If
Next ctlEnd Sub