【发布时间】:2015-06-21 01:43:51
【问题描述】:
我希望能够在动态多维数组中添加一些数据范围,而无需使用筛选数组每个元素的双循环。但我不知道这是否可能。双循环,我的意思是这样的代码(这只是一个例子):
Dim Films(1 To 5, 1 To 2) As String
Dim i As Integer, j As Integer
For i = 1 To 5
For j = 1 To 2
Films(i, j) = Cells(i, j).Value
Next j
Next i
我使用的是 VBA 2010。我知道我的数组有多少行,但列数是可变的。
这是我的代码:
Sub DRS(Item)
'item is a name to search for in a specific range
Dim SrcRange() As Variant
Dim cell3 As Range
Dim n As Integer, m As Integer
SrcRange() = Array()
ReDim SrcRange(45, 0)
m = -1
n = 0
With Sheets("X")
For Each cell3 In .Range("I13:AG" & .Cells(1, Columns.Count).End(xlToRight).Column)
'the range ("I13:AG...") contains names, and some will match with "item"
m = m + 1
If Len(cell3.Value) > 0 And cell3 = Item Then
SrcRange(0, n) = .Range(m + 8 & "30:" & m + 8 & "75")
'the previous line **should** add a whole range of cells (which contain numbers, one by cell) in a colum of the array, but this is the line that doesn't work.
n = n + 1
ReDim Preserve SrcRange(UBound(SrcRange), n)
End If
Next cell3
End With
End Sub
我已经试过了::
SrcRange(:, n) = .Range(m + 8 & "30:" & m + 8 & "75")
SrcRange(0:45, n) = .Range(m + 8 & "30:" & m + 8 & "75")
SrcRange(, n) = .Range(m + 8 & "30:" & m + 8 & "75")
但没有人工作。
有没有一种方法或公式可以让我向数组的每一列添加完整范围的单元格,还是我必须使用双循环来逐个添加元素?
【问题讨论】:
-
你到底想做什么?我认为你想要的是可行的,但你能说明一个示例数据以及你希望它如何传递给数组吗?
-
我想创建一个在查看数据时动态更新的数组。更准确地说,当我在电子表格“X”中添加一列时,我希望它作为数组中的新列添加。这个数组是用来设置图表的,但是我只给出了数组的代码,所以更具可读性。
标签: arrays vba dynamic multidimensional-array