使用VBA使用Excel表列中的值填充一维数组

时间:2014-11-24 22:07:56

标签: arrays excel vba excel-vba excel-2010

下面的代码用于将Excel表格中的列读取到数组中,然后可以使用这些列来确定每个"项目"属于Environment" Group",如果是,则将项目编号和美元值添加到另一个数组。我的代码存在一些问题,并且一直在搜索互联网和StackOverflow,但是能够找到使用VBA处理Excel表的非常少的信息。我正在使用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

我收到超出范围的"下标"这些行有错误:

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

我查了一下错误,认为这些行可能会解决问题:

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

现在,我在上面的行上收到了相同的错误,并且已经没有关于如何修复错误的想法。我怀疑它正在发生,因为我将一个范围分配到一个数组中,但我不确定。

1 个答案:

答案 0 :(得分:3)

变化:

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

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

从工作表中读取的数组总是多维的,即使您只有1列。

在这种情况下,您每次都要将该列指定为1。