简体   繁体   English

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

[英]Create named range of all cells that contain constants or formulas?

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(... 但是我在以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))

Union only works with Ranges that are on the same sheets. Union仅适用于同一张纸上的Ranges。 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 如果您需要以不同方式处理错误,请查看此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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