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

标签 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))

最佳答案

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

关于vba - 创建包含常量或公式的所有单元格的命名范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26781097/

相关文章:

当curl返回200时,VBA GET请求返回404

ms-access - VBA:按值传递给属性调用

c# - 使用 C# 中的 Open Xml SDK 将 DataTable 导出到 Excel

vba - 如何将数组返回到Excel VBA范围

excel - 交换字符串中的 2 个字符

sql - 列上的完整数据

excel - 我们如何在从 .rdlc 导出到 Excel 时包含单元格公式

Excel VBA - 将一维数组添加到多维数组而不循环

excel - Vba 宏在家用电脑上运行,在工作电脑上出现错误 2147417848

arrays - 是否可以将字典添加到 Excel VBA 中的数组?