我正在尝试创建一个命名范围,该范围引用包含公式或常量的所有单元格。但我在以 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/