如果活動單元格位于某個已定義名稱的區域中,可以用下面的VBA代碼來選擇這個區域,同時在狀態欄中給出提示。
Public Sub SelectRange()
Dim RngName As String
Dim R As Range
Set R = ActiveCell
Dim Msg As String
Msg = "活動單元格不在已定義名稱的區域中"
RngName = CellInNamedRange(R)
If RngName <> "" Then
Range(RngName).Select
Msg = "已選擇的區域名稱: " + RngName
End If
Application.StatusBar = Msg
End Sub
Public Function CellInNamedRange(Rng As Range) As String
Dim N As Name
Dim C As Range
Dim TestRng As Range
On Error Resume Next
For Each N In ActiveWorkbook.Names
Set C = Nothing
Set TestRng = N.RefersToRange
Set C = Application.Intersect(TestRng, Rng)
If Not C Is Nothing Then
CellInNamedRange = N.Name
Exit Function
End If
Next N
CellInNamedRange = ""
End Function
如果活動單元格位于多個已定義名稱的區域中,將按照名稱框下拉列表中的順序選擇第一個名稱區域。