
21 - Excel VBA – Arrays | Array Types | Array Declaration | Excel Automation | #excelsteps
21 - Excel VBA – Arrays | Array Types | Array Declaration | Excel Automation | #excelsteps
Download Link: drive.google.com/drive/folders/1OZu75CRlJFiuDTw3vs…
In VBA, an array is a data structure that allows you to store multiple values of the same data type in a single variable. You can use arrays to efficiently manage and manipulate large sets of data. Here's an explanation of arrays in VBA:
Declaration and Initialization:
```vba
Dim arrayName(size) As dataType
```
or
```vba
Dim arrayName() As dataType
ReDim arrayName(size)
```
`arrayName`: The name of the array variable.
`size`: The number of elements the array can hold. If not specified initially, you can use the `ReDim` statement to resize the array later.
`dataType`: The data type of the elements in the array.
Example - Declaring and initializing an array:
```vba
Dim numbers(4) As Integer ' An array of 5 integers (0 to 4)
numbers(0) = 10
numbers(1) = 20
numbers(2) = 30
numbers(3) = 40
numbers(4) = 50
```
Accessing Array Elements:
You can access individual elements in an array using the array name followed by the index number in parentheses. The index starts from 0 for the first element.
Example - Accessing array elements:
```vba
Dim value As Integer
value = numbers(2) ' Assigns the value 30 to the variable
```
Looping Through an Array:
You can use loops, such as `For` or `For Each`, to iterate through the elements of an array and perform operations on them.
Example - Looping through an array:
```vba
Dim i As Integer
For i = 0 To UBound(numbers)
' Code to be executed for each element
' Access the element: numbers(i)
Next i
```
In the above example, the loop iterates through each element of the `numbers` array, and you can perform operations on each element within the loop.
Arrays can be one-dimensional or multi-dimensional, depending on your requirements. They are useful for storing and manipulating data in VBA.
Remember to customize the array size, data type, and the code within the loop to suit your specific needs. Arrays provide a powerful way to work with multiple values efficiently in Excel VBA.
コメント