Ans : Arrays are a special kind of variable that can store multiple values of the same data type.
For Ex: If you have the names of 100 employees, theninstead of creating 100 variables of data type string,
we can just create one array variable of type string
and assign 100 values to the same array variable.
Syntax :
Dim arrayname(lowerbound To UpperBound) As DataType
'OR
Dim ArrayName() As Variant
There are multiple ways to declare an array.
Below are a few examples.
Example:
1) Dim MyArray1(0 To 3) As Integer
Creates an array with location 0,1,2,3 that will accept Integer values.
2) Dim MyArray2(3) As String
Defaults from 0 to 3 and creates an array with location 0,1,2,3 that will accept String values.
3) Dim MyArray3(13 to 15) As Double
Creates an array starting from 13
i.e. 13, 14, and 15, and accepts Double values.
We have mentioned the lower bound as 13,
so the array will start allocating values from location 13 rather than 0.
Sub Array_Variable()
Dim Wks As Worksheet
Set Wks = ThisWorkbook.Worksheets
("Sheet1")
Dim Employee(1 To 6) As String
Dim i As Integer
For i = 1 To 6
Employee(i) = Wks.Range("A" & i).Value
Debug.Print Employee(i)
Next i
End Sub
⚝ Access Array Variable Values :
Sub String_Array_Ex1()
Dim Myarr(1 To 5) As String
Dim k As Integer
Myarr(1) = "A"
Myarr(2) = "B"
Myarr(3) = "C"
Myarr(4) = "D"
Myarr(5) = "E"
For k = LBound(Myarr) To UBound(Myarr)
Debug.Print Myarr(k)
Next k
End Sub
Sub String_Array_Ex2()
Dim Myarr() As Variant
Dim k As Integer
Myarr = Array("Pune", "Mumbai",
"Kolkata", "Hyderabad", "Asam")
'When we create array like above,
we cannot use Array type as
String, we have to use Variant Data Type
For k = LBound(Myarr) To UBound(Myarr)
Debug.Print Myarr(k)
Next k
End Sub
Tags:
Array