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