Please Note: This article is written for users of the following Microsoft Excel versions: 97, 2000, 2002, and 2003. If you are using a later version (Excel 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Excel, click here: Using Named Ranges in a Macro.

Using Named Ranges in a Macro

by Allen Wyatt
(last updated January 6, 2018)

5

Bruce has a named range (Account) defined in a workbook and he wonders how to access and use that named range from within a macro. There are several ways you can access the range, using either the Range object or the Names collection.

To access the named range using the Range object, all you need to do is provide the name of the range as a parameter to the object. This name is the same one that you defined within Excel. For instance, the following line could be used to change the interior color of the entire range:

Worksheets("Sheet1").Range("Account").Interior.Color = vbYellow

Note that the Range object is used relative to a particular worksheet, in this case Sheet1. You could also define a range object within VBA and then assign it to be equal to the named range, in this manner:

Set rng = Worksheets("Sheet1").Range("Account")

The other method of using the named range is to use the Names collection. The following line will again set the interior color of the range to yellow:

Workbooks("Book1.xls").Names("Account").RefersToRange.Interior.Color = vbYellow

Note that the Names collection is relative to the entire workbook, so it is not necessary to know which worksheet the named range is associated with when you use this method of access. You can also define a range object in VBA and assign it to be the same as the named range:

Set rng = Workbooks("Book1.xls").Names("Account").RefersToRange

You should know that the Names collection method of accessing a named range will only be viable if you don't have the same named range defined on different worksheets in the workbook. If you do, then you will need to use the Range object method, which requires the use of a specific worksheet name in the reference.

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (3106) applies to Microsoft Excel 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Excel (Excel 2007 and later) here: Using Named Ranges in a Macro.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Limiting Precision

There may be times you need to limit the amount of precision Excel uses in its calculations. Here is one way to ...

Discover More

Adding a ScreenTip

If you want people to know something about a hyperlink you added to your worksheet, one way to help them is to use ...

Discover More

Changing Characters on Keyboard Keys

Want to assign some fancy characters to keyboard keys for characters you seldom use? There are a couple of ways you can ...

Discover More

Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!

More ExcelTips (menu)

Copying Worksheets in a Macro

Copying worksheets (one or many) is easy to do manually. What is not well known is that it is even easy to make the ...

Discover More

Hiding Entries in an InputBox

Requiring users to input a password in Excel increases the security of the worksheet and can prevent someone from running ...

Discover More

Understanding the For ... Next Structure

Part of the power of VBA is being able to control when some of your code executes and when it doesn't. A primary way to ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 8 + 0?

2020-10-24 13:32:54

Don

Set rng = Workbooks("Book1.xls").Names("Account").RefersToRange
gives me an error (1004 application-defined or object-defined error) when substituting for a variable workbookname, e.g.
Dim WBname As String
WBname = ActiveWorkbook.Name
Set rng = Workbooks(WBname).Names("Account").RefersToRange
or even
Set rng = activeworkbook.Names("Account").RefersToRange


2020-07-07 10:25:04

Phillip Richcreek

Worksheets("Vendors").Range("VendorNameFirst:VendorNameLast").Insert Shift:=xlShiftDown

In immediate window:

Print Range("VendorNameFirst:VendorNameLast").Address(0, 0)
B5:B6
print Range("VendorNameFirst").Address(0,0)
B5
?Range("VendorNameLast").Address(0,0)
B6


2020-07-06 12:46:02

Phillip Richcreek

Range("VendorNameFirst:VendorNameLast").Insert Shift:=xlShiftDown produces an error. The names in the Range are valid defined-names. Hard-coding the range, for example, range(b3:b4) defeats the purpose of relieving the user doing the insert manually, as inserts will be done repetivively. Is there a way to use the defined names?

Here is the code:

Option Explicit
Private Sub Workbook_Open()
Stop 'for debugging '7-5-2020
Dim onerrorsw
On Error GoTo OnErrorRoutineInOpen
Dim spName
spName = "yyyy-mm-dd spreadsheet test vba code.xlsm"
Dim opencount
Dim rngfirst As Range
Dim rnglast As Range
NORMAL_OPEN:
onerrorsw = 0
Stop '7-5-2020 uncommnent this for debugging
opencount = opencount + 1
onerrorsw = 1
Set rngfirst = Workbooks(spName).Names("VendorNameFirst").RefersToRange
onerrorsw = 2
Set rnglast = Workbooks(spName).Names("VendorNameLast").RefersToRange
'Set rng = Workbooks("yyyy-mm-dd spreadsheet test vba code.xlsm").Names("VendorNameFirst", "VendorNameLast").RefersToRange
onerrorsw = 3
Range(rngfirst, rnglast).Insert Shift:=xlShiftDownShift:=xlShiftDown
OnErrorRoutineInOpen:
onerrorsw = 1
Stop
Debug.Print "In Open ERROR " & Err.Number & " SOURCE " & Err.Source
On Error GoTo 0
Stop
End Sub

(I was using onerrorsw to identify the source of the error; not sure why I'm setting it to 1 in the onerror routine)


2020-06-16 15:39:23

Don

I have a few strings in single cells, where I am attempting to get the defined name values into VBA variables.
To quote another often useful website, "To get the value of a Name that contains a constant, use the RefersTo property.

V = ThisWorkbook.Names("TheName").RefersTo

However, all this does is assign the address of TheName to V ("=Sheet1!$C$2") as a string, rather than the actual string stored in cell C2. How do I get V to equal the value of TheName instead?


2018-02-25 19:45:35

Mike

I have a VBA code written to expand multiple groups of rows depending on if one of three selections is selected yes. I currently have the worksheet setup with 10 blank rows to expand if the yes option is selected, but want the ability to add rows if more data rows are needed beyond ten. The current code only references Rows to hide(i.e. 9:18) so if i insert another row, the code wont expand or collapse it and would mess up the ranges of the rows lower in the worksheet.

It seems like referencing a named range would work as the code wouldn't be looking for a range of row numbers, but rather a defined named range which would allow for rows to be inserted and dynamically update. I tried various inputs of the named range wording but keep getting an error in the coding. Can you let me know what the proper coding would be to reference the named range "SurveyMapping"? Code Section with attempted named range and a section with row number references Below:

If Not Intersect(Target, Range("$A1:ZZ100")) Is Nothing Then

If Range("b51").Value = "Yes" Then
Range("[Market Analysis Tool-2018-02-25.xlsm]!SurveyMapping").EntireRow.Hidden = False
ElseIf Range("c51").Value = "Yes" Then
Range("[Market Analysis Tool-2018-02-25.xlsm]!SurveyMapping").EntireRow.Hidden = False
ElseIf Range("d51").Value = "Yes" Then
Range("[Market Analysis Tool-2018-02-25.xlsm]!SurveyMapping").EntireRow.Hidden = False
Else
Range("[Market Analysis Tool-2018-02-25.xlsm!]SurveyMapping").EntireRow.Hidden = True
End If

End If

If Not Intersect(Target, Range("$A1:ZZ100")) Is Nothing Then

If Range("b64").Value = "Yes" Then
Rows("65:74").EntireRow.Hidden = False
ElseIf Range("c64").Value = "Yes" Then
Rows("65:74").EntireRow.Hidden = False
ElseIf Range("d64").Value = "Yes" Then
Rows("65:74").EntireRow.Hidden = False
Else
Rows("65:74").EntireRow.Hidden = True
End If

End If


This Site

Got a version of Excel that uses the menu interface (Excel 97, Excel 2000, Excel 2002, or Excel 2003)? This site is for you! If you use a later version of Excel, visit our ExcelTips site focusing on the ribbon interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.