Redim保留2D阵列

时间:2014-05-12 13:46:24

标签: arrays vba excel-vba excel

我有一些代码,它从范围中取值并将它们放到数组中。所以我有1.000.000行和4列。

x= Range("A1:D1000000").value

ReDim Arr(0 To UBound(x, 1), 0 To 4)

for i = 1 to 10
  for y = 1 to 4
    Arr(i - 1, y-1 ) = x(i, y)
  next y
next i

ReDim Preserve ARR(i)

Listbox1.list = Arr

我试过了

ReDim Preserve ARR(i)
ReDim Preserve ARR(i,4)
ReDim Preserve ARR(1,i)

Wihtout Redim Preserve我得到所有1.000.000结果的空白

如何调整大小保存到i大小所以我得到的结果只有10个结果?

3 个答案:

答案 0 :(得分:1)

您将不得不重新调整代码。您只能调整多维数组的 last 维度。

除非有令人信服的理由,否则我可能会做的只是调整您正在使用的Range对象的大小。这比尝试调整数组大小更容易。

Sub Test()
Dim x As Variant, ARR As Variant
Dim i As Integer
Dim y As Integer

Dim rng As Range  'Declare a range object we will use later

' Assign to our range object
Set rng = Range("A1:D1000000") 

'Resize your range object, it is easier to do this than to resize an array
Set rng = rng.Resize(10, 4)

'Now, your array x will take on the desired size of the range
'assign the rng.Value to array "x"
x = rng.Value

'And the array ARR will also take on this property based on x.
ReDim ARR(0 To UBound(x, 1), 0 To 4)

For i = 1 To 10
  For y = 1 To 4
    ARR(i - 1, y - 1) = x(i, y)
  Next y
Next i

End Sub

<强>更新

如果你需要保持Range对象的尺寸,那么你可以这样做,这将使x成为一个适当大小的数组,不用调整范围对象本身的大小。< / p>

' Assign to our range object
    Set rng = Range("A1:D1000000") 

'Use the resize method when assigning to array "x":
x = rng.Resize(10, 4).Value

答案 1 :(得分:0)

不读所有百万行。找到包含数据的范围的最后一行,只显示该数据。

Sub FillLb()

    Dim vaRange As Variant
    Dim aList() As Variant
    Dim i As Long, j As Long
    Dim rLastCell As Range

    Sheet1.ListBox1.Clear

    'Find the last cell that has something ("*") in it by searching
    'backward from A1 using xlPrevious
    Set rLastCell = Sheet1.Range("A1:D1000000").Find("*", Sheet1.Range("A1"), xlValues, , , xlPrevious)

    'Only read in up to the last value
    vaRange = Sheet1.Range("A1", rLastCell).Value
    ReDim aList(0 To UBound(vaRange, 1) - 1, 0 To UBound(vaRange, 2) - 1)
    Sheet1.ListBox1.ColumnCount = UBound(vaRange, 2)

    For i = LBound(vaRange, 1) To UBound(vaRange, 1)
        For j = LBound(vaRange, 2) To UBound(vaRange, 2)
            aList(i - 1, j - 1) = vaRange(i, j)
        Next j
    Next i

    Sheet1.ListBox1.List = aList

End Sub

答案 2 :(得分:0)

x= Range("A1:D1000000").value

ReDim Arr( 0 To 4 , 0 To UBound(x, 1))

for i = 1 to 10
  for y = 1 to 4
    Arr( y-1, i - 1 ) = x(i, y)
  next y
next i

ReDim Preserve ARR(0 to 4, 0 to i)

而不是:

Listbox1.List = Arr

你应该使用:

Listbox1.column = Arr