Excecl VBA Classic Excel VBA 2010 Excel VBA 365 Excel VBA Examples About Us

Lesson 3: Mastering Arrays in Excel VBA 365


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.

3.1 Understanding Arrays in VBA

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).

Key Benefit: Arrays make your code more organized, efficient, and scalable when working with large datasets.

3.2 One-Dimensional Arrays

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

Practical Examples

Example 3.1: Basic Array Implementation

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.

Example 3.2: Multiple Arrays with Related Data

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.

Advanced Array Techniques

VBA offers several powerful array features:

Dynamic Arrays

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

Array Functions

VBA provides useful array functions:

3.3 Two-Dimensional Arrays

Two-dimensional arrays are essential for working with tabular data (rows and columns). The declaration syntax is:

Dim arrayName(rowIndex, columnIndex) As DataType

Example 3.3: Sales Tracking System

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

Practical Applications of 2D Arrays

Two-dimensional arrays are perfect for:

3.4 Best Practices for Working with Arrays

  1. Always specify data types - Avoid Variant arrays unless necessary
  2. Use meaningful names - StudentGrades is better than sg
  3. Consider using Option Base 1 - Makes arrays more intuitive (first index = 1)
  4. Validate array bounds - Always check LBound and UBound
  5. Clean up large arrays - Use Erase arrayName when done

3.5 Common Array Operations

Here are some essential array operations every VBA programmer should know:

Sorting an Array

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

Finding Array Elements

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

Summary: Key Points About VBA Arrays

  • Arrays store multiple values under a single variable name
  • One-dimensional arrays work like simple lists
  • Two-dimensional arrays represent tables (rows and columns)
  • Always declare arrays with proper data types for better performance
  • Use LBound and UBound to avoid out-of-bounds errors
  • ReDim Preserve allows resizing arrays while keeping existing data
  • Arrays significantly improve code efficiency with large datasets
  • Proper array naming makes your code more readable and maintainable

Ready for More?

Now that you've mastered arrays, you're ready to explore how operators work in VBA. Arrays combined with operators form the foundation for powerful data processing in Excel.

🔗 Related Resources



Copyright ® 2020 Dr.Liew Voon Kiong . All rights reserved   [Privacy Policy]

Contact: Facebook Page