创建包含常量或公式的所有单元格的命名范围?

时间:2014-11-06 13:48:09

标签: vba excel-vba excel

我正在尝试创建一个引用包含公式或常量的所有单元格的命名范围。但是我在以set r = Union(...

)开头的行上收到错误消息

我怎样才能让它发挥作用?

Dim r As Range

Set r = Union(Sheet1.Cells.SpecialCells(xlCellTypeConstants), Sheet1.Cells.SpecialCells(xlCellTypeFormulas), _
        Sheet22.Cells.SpecialCells(xlCellTypeConstants), Sheet22.Cells.SpecialCells(xlCellTypeFormulas))

1 个答案:

答案 0 :(得分:4)

Union仅适用于同一张纸上的范围。您可以通过

构建这样的地址集合
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

如果您需要以不同方式处理错误,请查看this answer