Arrays are fundamental building blocks in Excel VBA programming that allow you to work efficiently with collections of data. This comprehensive guide will teach you how to declare, initialize, and manipulate arrays to supercharge your VBA projects.
When working with single data items in Excel VBA 365, a simple variable suffices. However, arrays become essential when you need to handle multiple related data items efficiently. An array is a structured group of variables that share:
For example, instead of declaring 100 separate variables for student names (Student1, Student2, etc.), you can declare a single array: StudentNames(1 to 100).
One-dimensional arrays are the simplest form, representing a straight list of items. The syntax for declaring a one-dimensional array is:
Dim arrayName(index) As DataType ' OR Dim arrayName(firstIndex To lastIndex) As DataType
This example demonstrates storing and displaying student names:
Private Sub Button1_Click()
Dim StudentName(1 To 5) As String
For i = 1 To 5
StudentName(i) = InputBox("Enter student Name " & i)
Cells(i, 1).Value = StudentName(i)
Next i
End Sub
When executed, this code prompts the user to enter five names which are then displayed in cells A1 through A5.
This enhanced example shows how to manage related data across multiple arrays:
Private Sub CommandButton1_Click()
' Declare three related arrays
Dim StudentName(3) As String, StudentID(3) As String, StudentMark(3) As Single
For i = 1 To 3
StudentName(i) = InputBox("Enter student Name " & i)
StudentID(i) = InputBox("Enter ID for " & StudentName(i))
StudentMark(i) = InputBox("Enter mark for " & StudentName(i))
' Output to worksheet
Cells(i, 1).Value = StudentName(i)
Cells(i, 2).Value = StudentID(i)
Cells(i, 3).Value = StudentMark(i)
Next i
' Calculate and display average
Dim total As Single
For i = 1 To 3
total = total + StudentMark(i)
Next i
Cells(5, 3).Value = "Average: " & Format(total / 3, "0.00")
End Sub
This improved version includes data validation and calculates the average mark automatically.
VBA offers several powerful array features:
Arrays that can be resized during runtime using the ReDim statement:
Dim Scores() As Integer ReDim Scores(1 To 10) ' Initial size ' ... code ... ReDim Preserve Scores(1 To 20) ' Resize while preserving existing data
VBA provides useful array functions:
LBound(array) - Returns the smallest available indexUBound(array) - Returns the largest available indexArray() - Quickly creates and initializes an arrayTwo-dimensional arrays are essential for working with tabular data (rows and columns). The declaration syntax is:
Dim arrayName(rowIndex, columnIndex) As DataType
This enhanced example tracks sales performance with improved user interaction:
Private Sub Button1_Click()
' Declare 5 salespeople x 7 days array
Dim SalesVolume(1 To 5, 1 To 7) As Single
Dim sp As Integer, day As Integer
' Populate array with sales data
For sp = 1 To 5
For day = 1 To 7
SalesVolume(sp, day) = InputBox("Enter sales for Salesperson " & sp & _
", Day " & day & ":", "Sales Data Entry")
Cells(sp + 1, day + 1).Value = SalesVolume(sp, day)
Next day
Next sp
' Calculate and display totals
For sp = 1 To 5
' Weekly total for each salesperson
Cells(sp + 1, 9).Value = Application.WorksheetFunction.Sum( _
Range(Cells(sp + 1, 2), Cells(sp + 1, 8)))
Next sp
' Add column headers
Cells(1, 2).Value = "Monday": Cells(1, 3).Value = "Tuesday"
Cells(1, 4).Value = "Wednesday": Cells(1, 5).Value = "Thursday"
Cells(1, 6).Value = "Friday": Cells(1, 7).Value = "Saturday"
Cells(1, 8).Value = "Sunday": Cells(1, 9).Value = "Total"
' Format the output
Range("A1:I6").Columns.AutoFit
Range("B2:H6").NumberFormat = "$#,##0.00"
Range("I2:I6").Font.Bold = True
End Sub
Two-dimensional arrays are perfect for:
StudentGrades is better than sgLBound and UBoundErase arrayName when doneHere are some essential array operations every VBA programmer should know:
Sub SortArray()
Dim myArray() As Variant
myArray = Array("Orange", "Apple", "Banana", "Pear")
' Simple bubble sort
Dim i As Integer, j As Integer
Dim temp As String
For i = LBound(myArray) To UBound(myArray) - 1
For j = i + 1 To UBound(myArray)
If myArray(i) > myArray(j) Then
temp = myArray(i)
myArray(i) = myArray(j)
myArray(j) = temp
End If
Next j
Next i
' Output sorted array
For i = LBound(myArray) To UBound(myArray)
Debug.Print myArray(i)
Next i
End Sub
Function FindInArray(arr() As Variant, searchValue As Variant) As Integer
For i = LBound(arr) To UBound(arr)
If arr(i) = searchValue Then
FindInArray = i
Exit Function
End If
Next i
FindInArray = -1 ' Not found
End Function
LBound and UBound to avoid out-of-bounds errorsReDim Preserve allows resizing arrays while keeping existing data
Copyright ® 2020 Dr.Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page