简体   繁体   中英

Can't join ranges into array in VBA using Union

I have two named ranges I want to join, ie append the 2nd range onto the end of the first one in an array. When I use Union I only get the first range in the array. If I just use Range it works but I can't join non-contiguous ranges.

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

You are just stacking two columns on top of each other I think so you can loop as follows:

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

You could also get rid of j and just put

Arr(i) = tbl.ListColumns("Ability2").DataBodyRange(i - totalColumnRows, 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM