3

I am trying to create a named range that refers to all cells containing formulas or constants. But I get an error message on the row that starts with Set r = Union(...

How can I get this to work?

Dim r As Range

Set r = Union(Sheet1.Cells.SpecialCells(xlCellTypeConstants), Sheet1.Cells.SpecialCells(xlCellTypeFormulas), _
        Sheet22.Cells.SpecialCells(xlCellTypeConstants), Sheet22.Cells.SpecialCells(xlCellTypeFormulas))
Community
  • 1
  • 1
user1283776
  • 19,640
  • 49
  • 136
  • 276

1 Answers1

4

Union only works with Ranges that are on the same sheets. You can build a collection of the addresses like this though

Sub Main()

    Dim arr As Variant

    arr = Array( _
                GetAddresses(Sheet1, xlCellTypeConstants), _
                GetAddresses(Sheet1, xlCellTypeFormulas), _
                GetAddresses(Sheet2, xlCellTypeConstants), _
                GetAddresses(Sheet2, xlCellTypeFormulas) _
                )

    Dim r As Variant
    For Each r In arr
        If Len(r) > 0 Then Debug.Print r
    Next

End Sub

Function GetAddresses(sh As Worksheet, cellType As XlCellType) As String
    On Error Resume Next
    GetAddresses = sh.Name & "!" & sh.Cells.SpecialCells(cellType).Address
    On Error GoTo 0
End Function

If you need to handle your errors differently, have a look at this answer

Community
  • 1
  • 1