Finance

Charts

Statistics

Macros

Search

Multidimensional Arrays In Excel VBA

If you have not only seven temperature values to store but also measurements taken at three different locations, a two-dimensional array is suitable.

Elements of such an array are addressed via two indices:

  • The first index represents the measurement number.
  • The second index represents the location where the measurement was taken.

The following procedure demonstrates this, displaying the values for each location in separate columns:

Sub MultiDimensionalArray()
    Dim T(1 To 7, 1 To 3) As Integer
    Dim i As Integer, k As Integer
    ThisWorkbook.Worksheets("Sheet1").Activate
    Randomize
    For i = 1 To 7
        For k = 1 To 3
            T(i, k) = Rnd * 10 + 20
            Cells(i, k).Value = T(i, k)
        Next k
    Next i
End Sub

Explanation:

  • The statement Dim T(1 To 7, 1 To 3) As Integer declares a two-dimensional array with 7 rows and 3 columns of type Integer. Both indices start at 1.
  • The procedure uses two nested For loops:
    • The outer loop variable i runs from 1 to 7 (measurement number).
    • The inner loop variable k runs from 1 to 3 (location index).
  • The inner loop completes its full cycle for each single iteration of the outer loop, allowing access to all 21 elements.
  • Each element T(i, k) is assigned a random value between 20 and 30.
  • The entire array is displayed on the worksheet, with each location’s measurements in its own column.

Extending to Higher Dimensions:

  • If you have 7 measurements per day at 3 locations for 31 days, you need a 3-dimensional array:
  • Dim T(1 To 7, 1 To 3, 1 To 31) As Integer ‘ Or better, As Single

This array has 7 × 3 × 31 elements.

  • Further, if you measure not only temperature but also wind direction, wind speed, and humidity, you would need a 4-dimensional array:
  • Dim T(1 To 7, 1 To 3, 1 To 31, 1 To 4) As Single
  • Arrays provide great flexibility to store and process large amounts of data temporarily during execution.

Persistent Storage Note:

For permanent storage, you need to save data to files (see Section 9.2, Simple Text Files) or better, databases.

0 0 votes
Évaluation de l'article
S’abonner
Notification pour
guest
0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Online comments
Show all comments
Facebook
Twitter
LinkedIn
WhatsApp
Email
Print
0
We’d love to hear your thoughts — please leave a commentx