VBA Union – Join Multiple Ranges
Union – Join Multiple Ranges
You might want to combine or join multiple ranges if the range string is too long, or you want to attempt to make your code easier to work with.
The need to combine multiple range strings is probably most common when selecting a large number of non contiguous cells with VBA.
One way to join multiple range strings is using VBA’s Union function. The syntax for the Union function is:
Union(Arg1 as Range, Arg2 as Range,etc,etc) as Range
The following is an example of using Union. First you declare some range variables, then set the range variables equal to something, and finally combine them using Union.
Sub UnionExample()
Dim Rng1, Rng2, Rng3 As Range
Set Rng1 = Range("A1,A3,A5,A7,A9,A11,A13,A15,A17,A19,A21")
Set Rng2 = Range("C1,C3,C5,C7,C9,C11,C13,C15,C17,C19,C21")
Set Rng3 = Range("E1,E3,E5,E7,E9,E11,E13,E15,E17,E19,E21")
Union(Rng1, Rng2, Rng3).Select
End Sub