你可以使用联合范围来定义数组吗?

时间:2014-10-29 16:38:28

标签: arrays excel vba union

我尝试使用来自2个不同列的数据来定义2-d数组。代码当前仅将我的数组定义为第一列(range1),忽略第二列(range2)。这是由于我的错误还是我不能使用工会化(是正确的术语?)范围来定义数组?

 Sub define_array()

Dim FTSE100() As Variant

Dim wsh As Worksheet

Dim range1 As Range
Dim range2 As Range
Dim finalrange As Range

Dim a As Integer
Dim finalrow As Integer

' define array

Set wsh = Sheet2
wsh.Activate

finalrow = Range("a1").End(xlDown).row

Set range1 = Range(Cells(1, 1), Cells(finalrow, 1))
Set range2 = Range(Cells(1, 5), Cells(finalrow, 5))
Set finalrange = Union(range1, range2)

' FTSE100 = finalrange

' Sheet15.Range("A:B") = FTSE 100

' Original code ended here

ReDim FTSE100(1 To finalrange.Areas.Count)

For a = 1 To finalrange.Areas.Count
FTSE100(a) = finalrange.Areas(a)
Next

With Sheet15.Range("A:B")
For a = 1 To .Columns.Count
.Columns(a).Resize(UBound(FTSE100(a))).Value = FTSE100(a)
Next
End With

End Sub

这似乎已经做到了,谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

你不能用非连续的范围这样做。

你可以这样做:

ReDim FTSE100(1 To finalRange.Areas.Count)

For a = 1 To finalRange.Areas.Count
    FTSE100(a) = finalRange.Areas(a)
Next

您必须执行类似的For ... Next循环才能写入值

With Sheet15.Range("A:B")
For a = 1 To .Columns.Count
    .Columns(a).Resize(UBound(FTSE100(a))).Value = FTSE100(a)
Next
End With

但是现在我明白你的问题实际上比这更简单:你只想将unisionizd范围内的值复制到另一个工作表。这很简单,不需要中间数组变量FTSE100

Set range1 = Range(Cells(1, 1), Cells(finalrow, 1))
Set range2 = Range(Cells(1, 5), Cells(finalrow, 5))

Sheet15.Range("A:A") = range1
Sheet15.Range("B:B") = range2