Written by Allen Wyatt (last updated July 8, 2022)
This tip applies to Excel 97, 2000, 2002, and 2003
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:
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.
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!
It is often helpful to get user input within a macro. Here's a quick way to present some options and get the user's response.
Discover MoreRecording macros is a great approach to getting started with macros, but at some point you'll need to create one from ...
Discover MoreSometimes, when you upgrade to a new version of Excel, you could run into a problem recording macros that you had no ...
Discover MoreFREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
2023-05-13 04:14:23
@David
In VBA coding, to achieve what you want, we often would replace something like
Workbooks("Book1.xls")
with
ThisWorkbook
Alan Elston
2023-05-13 00:52:18
David Russ
So in this example as well as others I see the name of the of the workbook file is explicitLy identified in the code. If the excel file with the vba code is saved as a copy with a new name I am gUessing that the code would have an error as it no loger would reference the correct workbook. How do I write the code so the name of the workbook in the code always references the current name of the workbook even if it is saved with a new name. This is not clear to me. Thanks
2021-10-06 11:44:15
Rubens Sayegh
Hi Peter. Thank you for the information. I really didn't pay attention to that when creating the code... :-)
2021-10-05 20:12:38
Peter
Hi Rubens, Your main problem is that the two range arguments are text: they need to be ranges. You can make variables with those names and set them to the named ranges or just use the range() function. The following should work OK:
Dim TimeHR As Range, TimeBP As Range
Set TimeHR = Range("timehr")
Set TimeBP = Range("timebp")
Cells(LIN, COL+1).Value =WorksheetFunction.XLookup(Cells(LIN,COL).Value, TimeHR, TimeBP, 999, , 1)
2021-10-04 19:55:12
I've named two ranges in my spreadsheet: C19 to C2000 as "TimeHR" and D19 to D2000 as "TimeBP";
Both columns C and D are filled with values;
A cell in LIN = 19, COL = 40 has a valid value;
Then I use a VBA formula as...
Cells(LIN, COL+1).Value = Worksheet.ApplicationFormula.Xlookup(Cells(LIN,COL).value,"TimeHR","TimeBP",999,,1)
But everytime I run this macro, the return value is "" (null). If I remove the range names and insert the ranges themselves ("C19:C2000" and "D19:D2000") the result is a valid value.
Why?
Rubens (rubosay@gmail.com)
2021-06-09 17:45:48
Following code produces error: Getting run-time 1004: Method 'Range' of object '_Worksheet' failed when using cells
Private Sub Worksheet_Change(ByVal Target As Range)
Dim selVal As String, sht As Worksheet
Set sht = ThisWorkbook.Sheets(Sheet1.Name)
selVal = Target.Value
If Not Intersect(Target, sht.Range("foh0"), sht.Range("boh0")) Is Nothing Then
......
End If
End Sub
Note: I have 2 named ranges ( foh0 & boh0 ) defined in Sheet1
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
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.
FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
Copyright © 2023 Sharon Parq Associates, Inc.
Comments