Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA Union Function: How to Combine Ranges

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The VBA Union function takes two or more Range objects on the same worksheet and returns one Range object that holds all of those areas. You use it with Set, like this: Set u = Union(Range("A1"), Range("C3")). That gives you a single object whose address is $A$1,$C$3, so you can format, clear, delete or inspect every area in one pass instead of writing separate statements. Union only builds a reference — it never merges cells or moves data.

What You'll Need

  • Desktop Excel for Windows or Mac with the VBA editor. Union is a VBA method and does not exist in Excel for the web, and it cannot be called from a normal worksheet formula.
  • A workbook saved as .xlsm (macro-enabled) if you want to keep the code.
  • A basic grasp of Range objects and the difference between assigning an object with Set and assigning a value.

Step-by-Step

  1. Open the VBA editor. Press Alt+F11 (Windows) or Option+F11 (Mac). If nothing happens on Windows, enable the Developer tab first via File > Options > Customize Ribbon. Menu wording can vary slightly by Excel version, so look for the closest match.

  2. Insert a module. In the editor choose Insert > Module. Code in a standard module can be run with F5 and is easy to test.

  3. Write the simplest Union statement. Declare a Range variable and assign the union to it with Set — a plain = will not work for objects.

    Sub BasicUnion()
        Dim u As Range
        Set u = Union(Range("A1"), Range("C3"))
        MsgBox u.Address      ' shows $A$1,$C$3
    End Sub
  4. Test it in the Immediate window first. Press Ctrl+G to open the Immediate window, type the line below and press Enter. You should see the comma-separated address immediately, which confirms both ranges are valid and on the active sheet.

    ? Union(Range("A1"), Range("C3")).Address
  5. Apply something to the combined range. The whole point of Union is one action across all areas. Properties such as Interior.Color, Font.Bold, ClearContents and Value apply to every area at once.

    Set u = Union(Range("A1"), Range("C3"), Range("E5"))
    u.Interior.Color = vbYellow
    u.Font.Bold = True
  6. Build the union in a loop. This is the most common real use: collect cells that meet a condition, then act once. Start from Nothing and test with Is Nothing before the first assignment, because Union cannot take an empty object as an argument.

    Sub BuildUnion()
        Dim c As Range, u As Range
        For Each c In Range("A1:A20")
            If c.Value > 5 Then
                If u Is Nothing Then
                    Set u = c
                Else
                    Set u = Union(u, c)
                End If
            End If
        Next c
        If Not u Is Nothing Then u.Interior.Color = vbYellow
    End Sub
  7. Inspect the individual blocks. A union of non-adjacent cells keeps them as separate areas. Use the Areas collection to count or loop through them, which is useful when each block needs different treatment.

    Debug.Print u.Areas.Count
    Dim a As Range
    For Each a In u.Areas
        Debug.Print a.Address
    Next a
  8. Combine whole rows or columns when needed. EntireRow and EntireColumn return Range objects, so they can be passed to Union — handy for deleting several scattered rows in one statement.

    Union(Range("A2"), Range("A7")).EntireRow.Delete
  9. Pair Union with Intersect for filtering. Intersect returns only the overlap, so Intersect(u, Range("A:A")) narrows a union to one column. Always test the result for Nothing before using it, because no overlap means no object.

Common Mistakes

  • Forgetting Set. u = Union(...) without Set fails; Range is an object variable.
  • Passing values instead of ranges. Union(Range("A1").Value, Range("B2")) is invalid, because Union expects Range objects, not cell contents.
  • Mixing worksheets. All arguments must sit on one worksheet. Ranges from two sheets cannot be combined into one Range object.
  • Passing Nothing. Union(u, c) where u is still Nothing throws an error; guard it with If u Is Nothing.
  • Expecting a merge. Union creates a multi-area reference, not merged cells. Use Merge if you actually want merged cells.
  • Selecting without checking the active sheet. u.Select fails if the ranges belong to a sheet that is not active.

Tips

  • Write Application.Union if your project contains a procedure or variable named Union, which would otherwise shadow the built-in method.
  • The documented signature accepts up to 30 arguments per call. For more, nest calls or build in a loop.
  • Union on thousands of cells in a loop is slow because each call creates a new object. For large jobs, concatenate addresses into a string and convert once with Range(Mid$(addr, 2)).
  • Use u.Count to get the total number of cells across all areas, and u.Areas.Count for the number of blocks.
  • Avoid Select and Activate entirely; act on the union directly for faster, flicker-free code.

Troubleshooting

  • Run-time error 5, "Invalid procedure call or argument". Usually one argument instead of two or more, or ranges on different worksheets. Check the sheet of each range with Debug.Print r.Parent.Name.
  • Run-time error 91, "Object variable or With block variable not set". A missing Set, or the result was assigned after an error path. Trace back to the first assignment.
  • Run-time error 424, "Object required". A non-object (often .Value or a string address) was passed to Union. Wrap literal addresses in Range().
  • Run-time error 1004 when selecting or copying. The sheet is not active, or the areas are too irregular to copy. Copy each area separately inside a For Each a In u.Areas loop.
  • The union is empty or the wrong shape. Print u.Address and u.Areas.Count in the Immediate window; if the address looks wrong, the loop condition is selecting the wrong cells.

Frequently Asked Questions

Is Union the same as merging cells?

No. Union returns a Range reference covering several areas; the cells stay separate and keep their own values. Merging changes the worksheet structure.

Can Union combine ranges from different sheets or workbooks?

No. All ranges passed to a single Union call must belong to the same worksheet. Loop through each sheet and apply the action separately instead.

What is the difference between Union and Intersect?

Union returns everything you pass to it. Intersect returns only the cells the ranges share, and returns Nothing when there is no overlap.

How many ranges can I pass in one call?

The documented signature allows up to 30 Range arguments. Beyond that, nest Union calls or accumulate addresses and convert them once.

Does Union work with entire rows or columns?

Yes. EntireRow and EntireColumn return Range objects, so Union(Range("A2").EntireRow, Range("A7").EntireRow).Delete is valid.

Why does my loop-built union stay empty?

The condition never matched, or the first assignment was skipped. Check with If u Is Nothing before using the object, and print the criteria values while testing.