Populate one dimensional array with values ​​from Excel table column using VBA

The code below reads columns from an Excel spreadsheet into arrays, which can then be used to determine if each Project belongs to the Team environment, and if so, add the project number and dollar value to another array. I am having some problems with my code and I have searched the web and StackOverflow but could find very little information on working with Excel tables using VBA. I am using Excel 2010.

Sub UpdateProjectsAndCharges()
'Define arrays to be used
Dim projectArray() As Variant
Dim uniqueProjectArray(100) As Variant
Dim dollarValue() As Variant
Dim envProjectArray(100) As Variant
Dim envDollarValue(100) As Double
Dim cumulativeCosts(100) As Double
'Define all tables in this sheet as list objects
Dim UnitsValues As ListObject
Dim ChargingTracking As ListObject
'Define counters to be used
Dim counter As Integer
Dim counter2 As Integer
'Set variables for each table in sheet
Set UnitsValues = Sheets("Cluster Data").ListObjects("UnitsValues")
Set ChargingTracking = Sheets("Cluster Data").ListObjects("ChargingTracking")
'Find last row in table
With Sheets("Cluster Data")
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
End With
'Define variables to be used in loops
Dim userGroup As Variant
Dim project As Variant
Dim Value As Variant
'Set arrays to respective columns from UnitsValues table
userGroups = Range("UnitsValues[Group]")
projectArray = Range("UnitsValues[Project]")
dollarValue = Range("UnitsValues[Dollar Value]")
'Redefine length of arrays to number of rows in table
ReDim Preserve projectArray(lastRow)
ReDim Preserve dollarValue(lastRow)
'Set counter values
counter = 1
counter2 = 1

For Each userGroup In userGroups
    project = projectArray(counter)
    Value = dollarValue(counter)
    If userGroup = "Environment" Then
        envProjectArray(counter2) = project
        envDollarValue(counter2) = Value
        counter2 = counter2 + 1
        MsgBox ((envProjectArray(counter2) & " " & envDollarValue(counter2)))
    End If
    counter = counter + 1
Next userGroup

      

I was getting "Subscript out range" error with these lines:

project = projectArray(counter)
Value = dollarValue(counter)

      

I was looking for the error and thought that these lines would probably fix the problem:

ReDim Preserve projectArray(lastRow)
ReDim Preserve dollarValue(lastRow)

      

Now I am getting the same error on the lines above and I am running out of ideas on how to fix the error. I suspect this is happening because I assigned the range to the array, but I'm not sure.

+3


source to share


1 answer


Edit:

project = projectArray(counter)
Value = dollarValue(counter)

      

to



project = projectArray(counter, 1)
Value = dollarValue(counter, 1)

      

Arrays read from tables are always multidimensional even if you only have 1 column.

In this case, you are specifying that the column will be 1 every time.

+3


source







All Articles