2014-11-24 132 views
3

下面的代码旨在将Excel表格中的列读入数组中,然后可以使用它们来确定每个“项目”是否属于环境“组“,如果是这样,将项目编号和美元值添加到另一个数组。我在使用我的代码时遇到了一些问题,并且一直在搜索互联网和StackOverflow,但已经能够找到有关使用VBA处理Excel表的很少信息。我使用Excel 2010中使用VBA填充Excel表格列中的值的一维数组使用VBA

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) 

现在,我收到上面,而不是线相同的错误,并已用完就如何修正这个错误的想法。我怀疑这是因为我将一个范围分配到一个数组中,但我不确定。

+0

@enderland,我早些时候看过这个问题,试图实现它的一部分,但不幸的是它并没有解决问题。 – David 2014-11-24 22:20:51

+0

顺便说一句,Dim projectArray As Variant就足够了。你只需要一个Variant,而不是Variant的数组。执行分配时的结果是一个Variant数组。 – 2014-11-25 03:18:24

+0

也是+1,因为我不知道你可以传递Range属性的结构化引用。 – 2014-11-25 03:22:08

回答

3

变化:

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

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

数组从工作表读取始终是多方面的,即使你只是有1列。

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

+2

一个小技巧来补充这个:如果真的需要一个1维数组(像Join这样的一些函数的参数很有用),那么将1列数组转换为它的一个简单方法就是使用WorksheetFunction.Transpose。在多行1列范围内使用它将得到1-d数组,或者在1行多列范围内使用两次(即转置转置)将得到1-d数组。 – 2014-11-24 23:22:57

+1

@Cor_Blimey err ... Cor Blimey!这是一个非常酷的提示。 +1 – 2014-11-25 03:10:34

相关问题