我有两个我想要加入的命名范围,即将第二个范围附加到数组中第一个范围的末尾。当我使用Union
时,我只获得数组中的第一个范围。如果我只使用Range
它可以工作,但我不能加入非连续的范围。
Sub GetAbilities()
Dim Arr() As Variant
Dim rng1 As Range
Dim rng2 As Range
Dim newRng As Range
Set rng1 = tbl.ListColumns("Ability1").DataBodyRange
Set rng2 = tbl.ListColumns("Ability2").DataBodyRange
Set newRng = Union(rng1, rng2)
' Set newRng = Range(rng1, rng2)
' This works fine
Arr = newRng
Dim Destination As Range
Set Destination = Sheets("test").Range("A1")
Destination.Resize(UBound(Arr, 1), UBound(Arr, 2)).Value = Arr
End Sub
你只是将两列叠加在一起,我想你可以按如下方式循环:
Option Explicit
Sub Test()
Dim Arr() As Variant
Dim tbl As ListObject
Set tbl = ThisWorkbook.Worksheets("Sheet4").ListObjects("Table1") 'this would be set as per your requirements
Dim totalOutputRows As Long
Dim totalColumnRows As Long
totalColumnRows = tbl.DataBodyRange.Rows.Count
totalOutputRows = totalColumnRows * 2
ReDim Arr(1 To totalOutputRows)
Dim i As Long
Dim j As Long
For i = 1 To totalOutputRows
If i <= totalColumnRows Then
Arr(i) = tbl.ListColumns("Ability1").DataBodyRange(i, 1)
Else
j = j + 1
Arr(i) = tbl.ListColumns("Ability2").DataBodyRange(j, 1)
End If
Next i
End Sub
你也可以摆脱j而放弃
Arr(i) = tbl.ListColumns("Ability2").DataBodyRange(i - totalColumnRows, 1)