首页 > 解决方案 > 是否可以获得活动单元格所在范围的名称?

问题描述

场景: Range 被命名为“Dog”,命名的 Range Dog 指的是 A1:D4。活动单元格位于指定范围内的单元格 B3 中。

是否可以获得活动单元格所在的命名范围的名称?即返回名称“狗”?

标签: excelvba

解决方案


可能类似于以下内容,它测试IntersectionActiveCell每个命名范围。

On Error Resume Next...On Error GoTo 0是必要的,因为当和命名范围在不同的工作表上时,或者如果不是命名范围但它引用常量或公式时,Intersect它将失败。ActiveCelln

Sub test()
    Dim n As Name
    For Each n In ActiveWorkbook.Names

        Dim rng As Range
        Set rng = Nothing

        On Error Resume Next
        Set rng = Intersect(ActiveCell, n.RefersToRange)
        On Error GoTo 0

        If Not rng Is Nothing Then
            Debug.Print n.Name
        End If
    Next
End Sub

推荐阅读