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 Categ ory 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. Oth er 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 ra nge of reference for an obje ct or variable . For exampl e, local vari ab les can be referenced only within the procedure they were defined. Public variables are accessible from anywhere in the application. Scope Private Public Proce dure- level Vari ables a re pri vate to t he procedure in which they appear. Not applicable. You cannot declare public variables within a procedure. Module-level Variables a re privat e to the module in which they appear. Variables are available to all modules.
33
Embed
Microsoft Visual Basic 6 (Basic Programming Fundamental)
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
8/8/2019 Microsoft Visual Basic 6 (Basic Programming Fundamental)
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)
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
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)
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)
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:
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)
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)
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)
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)
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)
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)
'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)
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:
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.
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.
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)
‘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:
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)
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)
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.
- 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"
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"
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) & " " &
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)
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.
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