How to obtain a list of named range exist in a specific worksheet that start with particular string (for example all named range that start with total) and grab the value? I am trying to do Sub Total and Grand Total of accommodation cost based on the date. I will assign an unique name for each Sub Total based on the Date group. Then, I have a button that need to be clicked when it finishes to calculate the Grand Total based on the Named Range that I’ve assigned uniquely to each Sub Total.
Below is the code I wrote to do the Grand Total:
Sub btnTotal()
Dim Total, LastRowNo As Long
LastRowNo = ActiveSheet.UsedRange.Row + ActiveSheet.UsedRange.Rows.Count
Total = 0
For Each N In ActiveWorkbook.Names
Total = Total + IntFlight.Range(N.Name).Value
Next N
IntFlight.Range("$P" & LastRowNo).Select
Selection.NumberFormat = "$* #,##0.00;$* (#,##0.00);$* ""-""??;@"
With Selection
.Font.Bold = True
End With
ActiveCell.FormulaR1C1 = Total
End Sub
Note: the IntFlight from «Total = Total + IntFlight.Range(N.Name).Value» is the name of my worksheet.
The only problem with above code, it will looking all named range exist in the workbook. I just need to find named range exist in one particular worksheet, which start with given string and the row number (total26: means Sub Total from row 26) and then grab the value to be sum-ed as Grand Total.
Any ideas how to do this? Been spending 2 days to find the answer.
Thanks heaps in advance.
EDIT 1 (Solution Provided by Charles Williams with help from belisarius):
This is what I have done with the code from Charles Williams:
Option Explicit
Option Compare Text
Sub btnIntFlightsGrandTotal()
Dim Total, LastRowNo As Long
LastRowNo = FindLastRowNo("International Flights")
Dim oNM As Name
Dim oSht As Worksheet
Dim strStartString As String
strStartString = "IntFlightsTotal"
Set oSht = Worksheets("International Flights")
For Each oNM In ActiveWorkbook.Names
If oNM.Name Like strStartString & "*" Then
If IsNameRefertoSheet(oSht, oNM) Then
Total = Total + Worksheets("International Flights").Range(oNM.Name).Value
End If
End If
Next oNM
IntFlights.Range("$P" & LastRowNo).Select
Selection.NumberFormat = "$* #,##0.00;$* (#,##0.00);$* ""-""??;@"
With Selection
.Font.Bold = True
End With
ActiveCell.FormulaR1C1 = Total
End Sub
Function FindLastRowNo(SheetName As String) As Long
Dim oSheet As Worksheet
Set oSheet = Worksheets(SheetName)
FindLastRowNo = oSheet.UsedRange.Row + oSheet.UsedRange.Rows.Count
End Function
Thank you all for your help. Now, I need to come up with my own version for this script.
Named ranges are very useful when creating Excel models. However, it can get pretty hard to track what named range belongs where as your model grows. Highlighting them on your worksheets can help you identify their properties easily. In this article, we’re going to show you how to find named ranges in Excel by highlighting them using VBA.
How to find named ranges in Excel by highlighting them using VBA
Named ranges are objects in the Names collection, which is an element of a workbook. You can loop through the existing names using a For…Next loop. Name items can return their ranges using the RefersToRange method. After you get the range, you can use the ColorIndex property to set that range a color. Here are some index numbers for colors:
- 3: Red
- 5: Blue
- 6: Yellow
- 0: No Fill
We suggest you to use On Error Resume Next line at the start of your code in case of any erroneous named range.
First, you need to add the module into the workbook or the add-in file. Copy and paste the code into the module to run it. The main advantage of the module method is that it allows saving the code in the file, so that it can be used again later. Furthermore, the subroutines in modules can be used by icons in the menu ribbons or keyboard shortcuts. Remember to save your file in either XLSM or XLAM format to save your VBA code.
Highlight named ranges
Sub HighlightNamedRanges() On Error Resume Next Dim nm As Name For Each nm In ActiveWorkbook.Names nm.RefersToRange.Interior.ColorIndex = 3 '3: Red, 6:Yellow Next nm End Sub
Naming a range of cells in Excel provide an easy way to reference those cells in a formula. If you have a workbook with a lot of data on the worksheets, naming ranges of cells can make your formulas easier to read and less confusing.
RELATED: How to Assign a Name to a Range of Cells in Excel
But if you have a particularly big spreadsheet, you may not remember which names refer to which ranges. We’ll show you how to generate a list of names and their associated cell ranges you can reference as you make formulas for that spreadsheet.
Depending on how many names you have in your workbook, you may want to use a new worksheet to store the list. Our list is not very long, but we still want to keep it separate from the rest of our data. So, right-click on the worksheet tabs at the bottom of the Excel window and select “Insert” from the popup menu. When the “Insert” dialog box displays, make sure the “General” tab is active and “Worksheet” is selected in the right box. Then, click “OK”.
Select the cell on your new worksheet where you want the list of names to start and click the Formulas tab. You can add some headings above your list if you want, like we did below.
In the Defined Names section, click “Use In Formula” and select “Paste Names” from the drop-down menu. You can also press “F3”.
NOTE: If there are no named cell ranges in your workbook, the “Use In Formula” button is not available.
On the Paste Name dialog box, all the named cell ranges display in the Paste name list. To insert the entire list into the worksheet, click “Paste List”.
The list is inserted starting in the selected cell. You might want to widen the columns so the names don’t get cut off. Simply put the cursor over the right edge of the column you want to widen until it becomes a double arrow and then double-click.
Your list of names and the corresponding cell ranges display in your worksheet. You can save your workbook like this so you have a list of your names and you can also print the worksheet if you want.
If you add names to or remove names from the workbook, delete the generated list and generate it again to obtain an updated list.
READ NEXT
- › 6 Uses for the HYPERLINK Function in Microsoft Excel
- › How to Use the SUBTOTAL Function in Microsoft Excel
- › How to Edit a Drop-Down List in Microsoft Excel
- › How to Use an Advanced Filter in Microsoft Excel
- › How to Adjust and Change Discord Fonts
- › The New NVIDIA GeForce RTX 4070 Is Like an RTX 3080 for $599
- › HoloLens Now Has Windows 11 and Incredible 3D Ink Features
- › Google Chrome Is Getting Faster
How-To Geek is where you turn when you want experts to explain technology. Since we launched in 2006, our articles have been read billions of times. Want to know more?
Named ranges are one of these crusty old features in Excel that few users understand. New users may find them weird and scary, and even old hands may avoid them because they seem pointless and complex.
But named ranges are actually a pretty cool feature. They can make formulas *a lot* easier to create, read, and maintain. And as a bonus, they make formulas easier to reuse (more portable).
In fact, I use named ranges all the time when testing and prototyping formulas. They help me get formulas working faster. I also use named ranges because I’m lazy, and don’t like typing in complex references
The basics of named ranges in Excel
What is a named range?
A named range is just a human-readable name for a range of cells in Excel. For example, if I name the range A1:A100 «data», I can use MAX to get the maximum value with a simple formula:
=MAX(data) // max value
The beauty of named ranges is that you can use meaningful names in your formulas without thinking about cell references. Once you have a named range, just use it just like a cell reference. All of these formulas are valid with the named range «data»:
=MAX(data) // max value
=MIN(data) // min value
=COUNT(data) // total values
=AVERAGE(data) // min value
Video: How to create a named range
Creating a named range is easy
Creating a named range is fast and easy. Just select a range of cells, and type a name into the name box. When you press return, the name is created:
To quickly test the new range, choose the new name in the dropdown next to the name box. Excel will select the range on the worksheet.
Excel can create names automatically (ctrl + shift + F3)
If you have well structured data with labels, you can have Excel create named ranges for you. Just select the data, along with the labels, and use the «Create from Selection» command on the Formulas tab of the ribbon:
You can also use the keyboard shortcut control + shift + F3.
Using this feature, we can create named ranges for the population of 12 states in one step:
When you click OK, the names are created. You’ll find all newly created names in the drop down menu next to the name box:
With names created, you can use them in formulas like this
=SUM(MN,WI,MI)
Update named ranges in the Name Manager (Control + F3)
Once you create a named range, use the Name Manager (Control + F3) to update as needed. Select the name you want to work with, then change the reference directly (i.e. edit «refers to»), or click the button at right and select a new range.
There’s no need to click the Edit button to update a reference. When you click Close, the range name will be updated.
Note: if you select an entire named range on a worksheet, you can drag to a new location and the reference will be updated automatically. However, I don’t know a way to adjust range references by clicking and dragging directly on the worksheet. If you know a way to do this, chime in below!
See all named ranges (control + F3)
To quickly see all named ranges in a workbook, use the dropdown menu next to the name box.
If you want to see more detail, open the Name Manager (Control + F3), which lists all names with references, and provides a filter as well:
Note: in older versions of Excel on the Mac, there is no Name Manager, and you’ll see the Define Name dialog instead.
Copy and paste all named ranges (F3)
If you want a more persistent record of named ranges in a workbook, you can paste the full list of names anywhere you like. Go to Formulas > Use in Formula (or use the shortcut F3), then choose Paste names > Paste List:
When you click the Paste List button, you’ll see the names and references pasted into the worksheet:
See names directly on the worksheet
If you set the zoom level to less than 40%, Excel will show range names directly on the worksheet:
Thanks for this tip, Felipe!
Names have rules
When creating named ranges, follow these rules:
- Names must begin with a letter, an underscore (_), or a backslash ()
- Names can’t contain spaces and most punctuation characters.
- Names can’t conflict with cell references – you can’t name a range «A1» or «Z100».
- Single letters are OK for names («a», «b», «x», etc.), but the letters «r» and «c» are reserved.
- Names are not case-sensitive – «home», «HOME», and «HoMe» are all the same to Excel.
Named ranges in formulas
Named ranges are easy to use in formulas
For example, lets say you name a cell in your workbook «updated». The idea is you can put the current date in the cell (Ctrl + and refer to the date elsewhere in the workbook.
The formula in B8 looks like this:
="Updated: "& TEXT(updated, "ddd, mmmm d, yyyy")
You can paste this formula anywhere in the workbook and it will display correctly. Whenever you change the date in «updated», the message will update wherever the formula is used. See this page for more examples.
Named ranges appear when typing a formula
Once you’ve created a named range, it will appear automatically in formulas when you type the first letter of the name. Press the tab key to enter the name when you have a match and want Excel to enter the name.
Named ranges can work like constants
Because named ranges are created in a central location, you can use them like constants without a cell reference. For example, you can create names like «MPG» (miles per gallon) and «CPG» (cost per gallon) with and assign fixed values:
Then you can use these names anywhere you like in formulas, and update their value in one central location.
Named ranges are absolute by default
By default, named ranges behave like absolute references. For example, in this worksheet, the formula to calculate fuel would be:
=C5/$D$2
The reference to D2 is absolute (locked) so the formula can be copied down without D2 changing.
If we name D2 «MPG» the formula becomes:
=C5/MPG
Since MPG is absolute by default, the formula can be copied down column D as-is.
Named ranges can also be relative
Although named ranges are absolute by default, they can also be relative. A relative named range refers to a range that is relative to the position of the active cell at the time the range is created. As a result, relative named ranges are useful building generic formulas that work wherever they are moved.
For example, you can create a generic «CellAbove» named range like this:
- Select cell A2
- Control + F3 to open Name Manager
- Tab into ‘Refers to’ section, then type: =A1
CellAbove will now retrieve the value from the cell above wherever it is it used.
Important: make sure the active cell is at the correct location before creating the name.
Apply named ranges to existing formulas
If you have existing formulas that don’t use named ranges, you can ask Excel to apply the named ranges in the formulas for you. Start by selecting the cells that contain formulas you want to update. Then run Formulas > Define Names > Apply Names.
Excel will then replace references that have a corresponding named range with the name itself.
You can also apply names with find and replace:
Important: Save a backup of your worksheet, and select just the cells you want to change before using find and replace on formulas.
Key benefits of named ranges
Named ranges make formulas easier to read
The biggest single benefit to named ranges is they make formulas easier to read and maintain. This is because they replace cryptic references with meaningful names. For example, consider this worksheet with data on planets in our solar system. Without named ranges, a VLOOKUP formula to fetch «Position» from the table is quite cryptic:
=VLOOKUP($H$4,$B$3:$E$11,2,0)
However, with B3:E11 named «data», and H4 named «planet», we can write formulas like this:
=VLOOKUP(planet,data,2,0) // position
=VLOOKUP(planet,data,3,0) // diameter
=VLOOKUP(planet,data,4,0) // satellites
At a glance, you can see the only difference in these formulas in the column index.
Named ranges make formulas portable and reusable
Named ranges can make it much easier to reuse a formula in a different worksheet. If you define names ahead of time in a worksheet, you can paste in a formula that uses these names and it will «just work». This is a great way to quickly get a formula working.
For example, this formula counts unique values in a range of numeric data:
=SUM(--(FREQUENCY(data,data)>0))
To quickly «port» this formula to your own worksheet, name a range «data» and paste the formula into the worksheet. As long as «data» contains numeric values, the formula will work straightway.
Tip: I recommend that you create the needed range names *first* in the destination workbook, then copy in the formula as text only (i.e. don’t copy the cell that contains the formula in another worksheet, just copy the text of the formula). This stops Excel from creating names on-the-fly and lets you to fully control the name creation process. To copy only formula text, copy text from the formula bar, or copy via another application (i.e. browser, text editor, etc.).
Named ranges can be used for navigation
Named ranges are great for quick navigation. Just select the dropdown menu next to the name box, and choose a name. When you release the mouse, the range will be selected. When a named range exists on another sheet, you’ll be taken to that sheet automatically.
Named ranges work well with hyperlinks
Named ranges make hyperlinks easy. For example, if you name A1 in Sheet1 «home», you can create a hyperlink somewhere else that takes you back there.
To use a named range inside the HYPERLINK function, add a hash (#) in front of the named range:
=HYPERLINK("#home","take me home")
You can use this same syntax to create a hyperlink to a table:
=HYPERLINK("#Table1","Go to Table1")
Note: in older versions of Excel you can’t link to a table like this. However, you can define a name equal to a table (i.e. =Table1) and hyperlink to that.
Named ranges for data validation
Names ranges work well for data validation, since they let you use a logically named reference to validate input with a drop down menu. Below, the range G4:G8 is named «statuslist», then apply data validation with a List linked like this:
The result is a dropdown menu in column E that only allows values in the named range:
Dynamic Named Ranges
Names ranges are extremely useful when they automatically adjust to new data in a worksheet. A range set up this way is referred to as a «dynamic named range». There are two ways to make a range dynamic: formulas and tables.
Dynamic named range with a Table
A Table is the easiest way to create a dynamic named range. Select any cell in the data, then use the shortcut Control + T:
When you create an Excel Table, a name is automatically created (e.g. Table1), but you can rename the table as you like. Once you have created a table, it will expand automatically when data is added.
Dynamic named range with a formula
You can also create a dynamic named range with formulas, using functions like OFFSET and INDEX. Although these formulas are moderately complex, they provide a lightweight solution when you don’t want to use a table. The links below provide examples with full explanations:
- Example of dynamic range formula with INDEX
- Example of dynamic range formula with OFFSET
Table names in data validation
Since Excel Tables provide an automatic dynamic range, they would seem to be a natural fit for data validation rules, where the goal is to validate against a list that may be always changing. However, one problem with tables is that you can’t use structured references directly to create data validation or conditional formatting rules. In other words, you can’t use a table name in conditional formatting or data validation input areas.
However, as a workaround, you can define named a named range that points to a table, and then use the named range for data validation or conditional formatting. The video below runs through this approach in detail.
Video: How to use named ranges with tables
Deleting named ranges
Note: If you have formulas that refer to named ranges, you may want to update the formulas first before removing names. Otherwise, you’ll see #NAME? errors in formulas that still refer to deleted names. Always save your worksheet before removing named ranges in case you have problems and need to revert to the original.
Named ranges adjust when deleting and inserting cells
When you delete *part* of a named range, or if insert cells/rows/columns inside a named range, the range reference will adjust accordingly and remain valid. However, if you delete all of the cells that enclose a named range, the named range will lose the reference and display a #REF error. For example, if I name A1 «test», then delete column A, the name manager will show «refers to» as:
=Sheet1!#REF!
Delete names with Name Manager
To remove named ranges from a workbook manually, open the name manager, select a range, and click the Delete button. If you want to remove more than one name at the same time, you can Shift + Click or Ctrl + Click to select multiple names, then delete in one step.
Delete names with errors
If you have a lot of names with reference errors, you can use the filter button in the name manager to filter on names with errors:
Then shift+click to select all names and delete.
Named ranges and Scope
Named ranges in Excel have something called «scope», which determines whether a named range is local to a given worksheet, or global across the entire workbook. Global names have a scope of «workbook», and local names have a scope equal to the sheet name they exist on. For example, the scope for a local name might be «Sheet2».
The purpose of scope
Named ranges with a global scope are useful when you want all sheets in a workbook to have access to certain data, variables, or constants. For example, you might use a global named range a tax rate assumption used in several worksheets.
Local scope
Local scope means a name is works only on the sheet it was created on. This means you can have multiple worksheets in the same workbook that all use the same name. For example, perhaps you have a workbook with monthly tracking sheets (one per month) that use named ranges with the same name, all scoped locally. This might allow you to reuse the same formulas in different sheets. The local scope allows the names in each sheet to work correctly without colliding with names in the other sheets.
To refer to a name with a local scope, you can prefix the sheet name to the range name:
Sheet1!total_revenue
Sheet2!total_revenue
Sheet3!total_revenue
Range names created with the name box automatically have global scope. To override this behavior, add the sheet name when defining the name:
Sheet3!my_new_name
Global scope
Global scope means a name will work anywhere in a workbook. For example, you could name a cell «last_update», enter a date in the cell. Then you can use the formula below to display the date last updated in any worksheet.
=last_update
Global names must be unique within a workbook.
Local scope
Locally scoped named ranges make sense for worksheets that use named ranges for local assumptions only. For example, perhaps you have a workbook with monthly tracking sheets (one per month) that use named ranges with the same name, all scoped locally. The local scope allows the names in each sheet to work correctly without colliding with names in the other sheets.
Managing named range scope
By default, new names created with the namebox are global, and you can’t edit the scope of a named range after it’s created. However, as a workaround, you can delete and recreate a name with the desired scope.
If you want to change several names at once from global to local, sometimes it makes sense to copy the sheet that contains the names. When you duplicate a worksheet that contains named ranges, Excel copies the named ranges to the second sheet, changing the scope to local at the same time. After you have the second sheet with locally scoped names, you can optionally delete the first sheet.
Jan Karel Pieterse and Charles Williams have developed a utility called the Name Manager that provides many useful operations for named ranges. You can download the Name Manager utility here.