|
|
|
|
|
|
Excel
|
Check if Named Range exists
|
|
Ease of Use
|
Easy
|
Version tested with
|
2003
|
Submitted by:
|
Zack Barresse
|
Description:
|
Check whether or not a Named Range specific name exists in a specified workbook or not.
|
Discussion:
|
Use this function to test the existence of a specific named range. You can specify the workbook name if you'd like to. If you do not, the activeworkbook will be used. It will loop through all sheets. It does this because you MUST specify the sheet name whilst using VBA this way, in a worksheet function you do not.
|
Code:
|
instructions for use
|
Option Explicit
Option Compare Text
Function NamedRangeExists(strName As String, _
Optional wbName As String) As Boolean
Dim rngTest As Range, i As Long
If wbName = vbNullString Then wbName = ActiveWorkbook.Name
With Workbooks(wbName)
On Error Resume Next
For i = 1 To .Sheets.Count Step 1
Set rngTest = .Sheets(i).Range(strName)
If Err = 0 Then
NamedRangeExists = True
Exit Function
Else
Err.Clear
End If
Next i
End With
End Function
Sub NREtest1()
MsgBox NamedRangeExists("test")
End Sub
Sub NREtest2()
MsgBox NamedRangeExists("testing")
End Sub
Sub Test_CreateNamedRangeIfNotAlready()
If NamedRangeExists("Foxtrot") Then
MsgBox "Named Range already exists!"
Else
ActiveWorkbook.Names.Add "Foxtrot", "=Sheet1!$A$1:$D$4"
End If
End Sub
|
How to use:
|
- Copy all 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.
- Choose Insert --> Module.
- Paste code into the right pane.
- Press Alt + Q to close the VBE.
- Save workbook before any other changes.
- Press Alt + F8, select 'NREtest1' or 'NREtest2', press Run.
|
Test the code:
|
- From an existing workbook, save first.
- Press Alt + F8.
- Choose 'Test_CreateNamedRangeIfNotAlready'.
- Press 'Run'.
- Press Alt + F8.
- Choose 'Test_CreateNamedRangeIfNotAlready'.
- Press 'Run'. (Yes, twice.)
|
Sample File:
|
NREex.zip 10.84KB
|
Approved by mdmackillop
|
This entry has been viewed 244 times.
|
|