测试 Range 是否在 Excel 中有名称

Test if Range has a Name in Excel

我正在尝试确定一个范围是否有名称并不断收到错误消息。

我的代码如下所示:

Dim rCell As Range
Dim sName As String

Set rCell = Range("A1")
If Not rCell.Name Is Nothing Then sName = rCell.Name

并产生以下错误信息:

运行-时间错误'1004':

应用程序定义或对象定义的错误

我也试过更换 If Not rCell.Name Is Nothing Then sName = rCell.NamesName = rCell.Name 甚至 Debug.Print rCell.Name 一致,但仍然出现相同的错误。

我做错了什么?

如果范围未命名,

Range.Name 将抛出 RTE 1004。一种替代方法是尝试分配给 Name 对象。

请注意,您可能需要 Name.Name 属性。

Set rCell = Range("A1")

On Error Resume Next
Dim n As Name
Set n = Nothing ' only including in case you are planning to use this approach in a loop.
Set n = rCell.Name
On Error GoTo 0

If not n Is Nothing Then
   sName = n.Name ' Name.Name, not Range.Name
End If