|
|
|
|
|
|
Excel
|
Return Named Range Name from Refers To Value
|
|
Ease of Use
|
Easy
|
Version tested with
|
2003
|
Submitted by:
|
Zack Barresse
|
Description:
|
If you would like to check if a named range is occupying a specific range in Excel, this UDF can return the name the string is referring to or "Not Found" if no matching is found.
|
Discussion:
|
One may have a need to look at the name of a cell (Named Range) or to check if a name occupies a specific location in a workbook. This can be used as a worksheet function or via VBA code. This can also be used for Named Ranges that do not refer to locations, but rather values. Value can be passed as a String or Range. Will return approximate results if range intersects a Named Range.
|
Code:
|
instructions for use
|
Option Explicit
Option Compare Text
Public Function NAMEDRANGE(celRef As Variant) As String
Dim iName As Name, wbCall As Workbook, blnApprox As Boolean
Dim NRange As String
On Error Resume Next
If TypeOf celRef Is Range Then
celRef = celRef.Address
End If
If Not celRef Like "*!$" Then
celRef = Application.Caller.Parent.Name & "!" & celRef
If Err = 424 Then celRef = Range(celRef).Parent.Name & "!" & celRef
Err.Clear
End If
Set wbCall = Workbooks(Application.Caller.Parent.Parent.Name)
If Err = 424 Then Set wbCall = ActiveWorkbook
On Error GoTo 0
For Each iName In wbCall.Names
If iName.RefersTo = "=" & celRef Then
NAMEDRANGE = iName.Name
Set wbCall = Nothing
Exit Function
ElseIf Not Intersect(Range(celRef), Range(iName.RefersTo)) Is Nothing Then
NRange = NRange & "'" & iName.Name & "', "
NAMEDRANGE = "Intersects " & Left(NRange, Len(NRange) - 2)
blnApprox = True
End If
Next
Err_Exit:
If Not blnApprox Then NAMEDRANGE = "Not Found"
Set wbCall = Nothing
End Function
Sub CalledFromVBAx1()
MsgBox NAMEDRANGE("$A$1")
End Sub
Sub CalledFromVBAx2()
MsgBox NAMEDRANGE(Range("$A$1:$B$2"))
End Sub
Sub CalledFromVBAx3()
MsgBox NAMEDRANGE("$A$1:$C$3")
End Sub
|
How to use:
|
- Copy above code.
- In Excel press Alt + F11 to enter the VBE.
- Press Ctrl + R to show the Project Explorer.
- Right-click desired file on left (in bold).
- Choose Insert -> Module.
- Paste code into the right pane.
- Press Alt + Q to close the VBE.
- Save workbook before any other changes.
|
Test the code:
|
- VBA Method:
- From the main Excel interface, press Alt + F8 to open the macro dialog box
- Choose CalledFromVBAx1 (or x2, x3) and click Run
- A message box will return telling you the named specified by the Refers To range.
- Worksheet Function Method:
- In a blank cell, type:
- =NAMEDRANGE("$A$1")
- If a named range exists with that reference (exactly) then the name will be returned, else "Not Found"
|
Sample File:
|
NamedRangeEx.zip 10.14KB
|
Approved by mdmackillop
|
This entry has been viewed 177 times.
|
|