November 15, 2015/
Chris Newman
What Is A Named Range?
Creating a named range allows you to refer to a cell or group of cells with a custom name instead of the usual column/row reference. The HUGE benefit to using Named Ranges is it adds the ability to describe the data inside your cells. Let’s look at a quick example:
Can you tell if shipping costs are charged with the product price?
-
= (B7 + B5 * C4) * (1 + A3)
-
=(ShippingCharge + ProductPrice * Quantity) * (1 + TaxRate)
Hopefully, you can clearly see option number TWO gives you immediate insight to whether the cost of the products includes shipping costs. This allows the user to easily understand how the formula is calculating without having to waste time searching through cells to figure out what is what.
How Do I Use Named Ranges?
As a financial analyst, I play around with a bunch of rates. Examples could be anything from a tax rate to an estimated inflation rate. I use named ranges to organize my variables that either are changed infrequently (ie Month or Year) or something that will be static for a good amount of time (ie inflation rate). Here are a list of common names I use on a regular basis:
-
ReportDate
-
Year
-
Month
-
FcstID
-
TaxRate
-
RawData
Creating Unique Names On The Fly
It is super easy to create a Named Range. All you have to do is highlight the cell(s) you want to reference and give it a name in the Name Box. You name cannot have any spaces in it, so if you need to separate words you can either capitalize the beginning of each new word or use an underscore (_). Make sure you hit the ENTER key after you have finished typing the name to confirm the creation of the Named Range.
As a side note, any Named Range created with the Name Box has a Workbook scope. This means the named range can be accessed by any worksheet in your Excel file.
Creating Names With The «Name Manager»
If you want to customize your named ranges even more, you can open up the Name Manager (Formulas tab > Defined Names group > Name Manager button) to edit and create new named ranges.
I won’t go into great detail in this article, but know that with the Name Manager you can
-
Change the name of an existing Named Range
-
Change the reference formula
-
Specify the scope (what worksheets the name can be accessed from)
On To The VBA
Now that you have had a brief overview on Named Ranges, lets dig into some VBA macros you can use to help automate the use of Named Ranges.
Add A Named Range
The below VBA code shows ways you can create various types of named ranges.
Sub NameRange_Add()
‘PURPOSE: Various ways to create a Named Range
‘SOURCE: www.TheSpreadsheetGuru.com
Dim cell As Range
Dim rng As Range
Dim RangeName As String
Dim CellName As String
‘Single Cell Reference (Workbook Scope)
RangeName = «Price»
CellName = «D7»
Set cell = Worksheets(«Sheet1»).Range(CellName)
ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell
‘Single Cell Reference (Worksheet Scope)
RangeName = «Year»
CellName = «A2»
Set cell = Worksheets(«Sheet1»).Range(CellName)
Worksheets(«Sheet1»).Names.Add Name:=RangeName, RefersTo:=cell
‘Range of Cells Reference (Workbook Scope)
RangeName = «myData»
CellName = «F9:J18»
Set cell = Worksheets(«Sheet1»).Range(CellName)
ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell
‘Secret Named Range (doesn’t show up in Name Manager)
RangeName = «Username»
CellName = «L45»
Set cell = Worksheets(«Sheet1»).Range(CellName)
ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell, Visible:=False
End Sub
Loop Through Named Ranges
This VBA macro code shows how you can cycle through the named ranges within your spreadsheet.
Sub NamedRange_Loop()
‘PURPOSE: Delete all Named Ranges in the Active Workbook
‘SOURCE: www.TheSpreadsheetGuru.com
Dim nm As Name
‘Loop through each named range in workbook
For Each nm In ActiveWorkbook.Names
Debug.Print nm.Name, nm.RefersTo
Next nm
‘Loop through each named range scoped to a specific worksheet
For Each nm In Worksheets(«Sheet1»).Names
Debug.Print nm.Name, nm.RefersTo
Next nm
End Sub
Delete All Named Ranges
If you need to clean up a bunch of junk named ranges, this VBA code will let you do it.
Sub NamedRange_DeleteAll()
‘PURPOSE: Delete all Named Ranges in the ActiveWorkbook (Print Areas optional)
‘SOURCE: www.TheSpreadsheetGuru.com
Dim nm As Name
Dim DeleteCount As Long
‘Delete PrintAreas as well?
UserAnswer = MsgBox(«Do you want to skip over Print Areas?», vbYesNoCancel)
If UserAnswer = vbYes Then SkipPrintAreas = True
If UserAnswer = vbCancel Then Exit Sub
‘Error Handler in case Delete Function Errors out
On Error GoTo Skip
‘Loop through each name and delete
For Each nm In ActiveWorkbook.Names
If SkipPrintAreas = True And Right(nm.Name, 10) = «Print_Area» Then GoTo Skip
‘Error Handler in case Delete Function Errors out
On Error GoTo Skip
‘Delete Named Range
nm.Delete
DeleteCount = DeleteCount + 1
Skip:
‘Reset Error Handler
On Error GoTo 0
Next
‘Report Result
If DeleteCount = 1 Then
MsgBox «[1] name was removed from this workbook.»
Else
MsgBox «[» & DeleteCount & «] names were removed from this workbook.»
End If
End Sub
Delete Named Ranges with Error References
This VBA code will delete only Named Ranges with errors in them. These errors can be caused by worksheets being deleted or rows/columns being deleted.
Sub NamedRange_DeleteErrors()
‘PURPOSE: Delete all Named Ranges with #REF error in the ActiveWorkbook
‘SOURCE: www.TheSpreadsheetGuru.com
Dim nm As Name
Dim DeleteCount As Long
‘Loop through each name and delete
For Each nm In ActiveWorkbook.Names
If InStr(1, nm.RefersTo, «#REF!») > 0 Then
‘Error Handler in case Delete Function Errors out
On Error GoTo Skip
‘Delete Named Range
nm.Delete
DeleteCount = DeleteCount + 1
End If
Skip:
‘Reset Error Handler
On Error GoTo 0
Next
‘Report Result
If DeleteCount = 1 Then
MsgBox «[1] errorant name was removed from this workbook.»
Else
MsgBox «[» & DeleteCount & «] errorant names were removed from this workbook.»
End If
End Sub
Anything Missing From This Guide?
Let me know if you have any ideas for other useful VBA macros concerning Named Ranges. Or better yet, share with me your own macros and I can add them to the article for everyone else to see! I look forward to reading your comments below.
About The Author
Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.
Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!
— Chris
Founder, TheSpreadsheetGuru.com
In this VBA Tutorial, you learn how to create named ranges (for different ranges and with different scopes) with macros.
This VBA Tutorial is accompanied by Excel workbooks containing the macros I use in the examples below. You can get immediate free access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.
Use the following Table of Contents to navigate to the section you’re interested in.
Related VBA and Macro Tutorials
The following VBA and Macro Tutorials may help you better understand and implement the contents below:
- General VBA constructs and structures:
- Learn about commonly-used VBA terms here.
- Learn about working with Sub procedures here.
- Learn about the Excel VBA Object Model here.
- Learn about working with VBA methods here.
- Learn how to identify cell ranges here.
- Learn how to declare and work with variables here.
- Learn about VBA data types here.
- Learn about A1 and R1C1-style references here.
- Practical VBA applications and macro examples:
- Learn how to work with worksheets here.
- Learn several ways to find the last row with data here.
- Learn several ways to find the last column with data here.
You can find additional VBA and Macro Tutorials in the Archives.
VBA Code to Create Named Range
To create a named range using VBA, use a statement with the following structure:
Scope.Names.Add Name:=RangeName, RefersTo:=NamedRange
Process Followed by VBA to Create Named Range
VBA Statement Explanation
- Item: Scope.
- VBA Construct: Workbook or Worksheet object.
- Description: Scope of the named range you create. The scope of a named range can generally be 1 of the following:
- Workbook. In this case, Scope must represent a Workbook object. For these purposes, you can use VBA constructs such as the ActiveWorkbook property, the ThisWorkbook property or the Application.Workbooks property.
- Worksheet. In this case, Scope must represent a Worksheet object. For these purposes, you can use VBA constructs such as the ActiveSheet property or the Workbook.Worksheets property.
For a more detailed description of how to create a named range with worksheet scope, please refer to the appropriate section below.
- Item: Names.
- VBA Construct: Workbook.Names property (when Scope is a Workbook object) or Worksheet.Names property (when scope is a Worksheet object).
- Description: The Names property returns a Names collection representing all the names in the workbook (when Scope is a Workbook object) or worksheet (when Scope is a Worksheet object) represented by Scope. The Names collection returned by the Workbook.Names property includes worksheet-specific names.
- Item: Add.
- VBA Construct: Names.Add method.
- Description: The Names.Add method sets a new name for a cell range.
- Item: Name:=RangeName.
- VBA Construct: Name parameter of the Names.Add method.
- Description: The Name parameter of the Names.Add method allows you to specify the name of the named range you specify. Consider the following usual requirements when specifying RangeName:
- RangeName must start with a letter or underscore.
- Certain characters aren’t allowed. For example, RangeName can’t include spaces.
- RangeName can’t conflict with an existing name.
- RangeName can’t be formatted as a cell reference. For example, names such as “ABC1” aren’t allowed.
- If you want to specify the Name parameter using localized text, (i) work with the NameLocal parameter of the Names.Add method, and (ii) omit the Name parameter of the Names.Add method.
If you explicitly declare a variable to represent RangeName, use the String data type.
- Item: RefersTo:=NamedRange.
- VBA Construct: RefersTo parameter of the Names.Add method.
- Description: The RefersTo parameter of the Names.Add method allows you to specify the cell range to which the name refers to. The RefersTo parameter is of the Variant data type. Therefore, you commonly specify NamedRange as one of the following:
- A Range object.
- A string that uses the A1-style notation.
When working with the Names.Add method, you can also specify the cell range to which the name refers to using the following parameters.
- RefersToLocal: Allows you to specify the cell range in localized text using the A1-style notation.
- RefersToR1C1: Allows you to specify the cell range in R1C1-style notation.
- RefersToR1C1Local: Allows you to specify the cell range in localized text using the R1C1-style notation.
When working with one of the 4 parameters I refer to (RefersTo, RefersToLocal, RefersToR1C1, or RefersToR1C1Local), specify that single parameter and omit the others.
If you explicitly declare a variable to represent NamedRange, use the Range object data type (if specifying NamedRange as a Range object) or the String data type (if specifying NamedRange as a string).
Macro Example to Create Named Range
The following macro example creates a named range with workbook scope (ThisWorkbook) by setting the name of the cell range composed of cells A5 to C10 (myNamedRange) of the Named Range worksheet (myWorksheet) to “namedRange” (myRangeName).
Sub createNamedRange() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/vba-create-named-range/ 'declare object variables to hold references to worksheet containing cell range, and cell range itself Dim myWorksheet As Worksheet Dim myNamedRange As Range 'declare variable to hold defined name Dim myRangeName As String 'identify worksheet containing cell range, and cell range itself Set myWorksheet = ThisWorkbook.Worksheets("Named Range") Set myNamedRange = myWorksheet.Range("A5:C10") 'specify defined name myRangeName = "namedRange" 'create named range with workbook scope. Defined name and cell range are as specified ThisWorkbook.Names.Add Name:=myRangeName, RefersTo:=myNamedRange End Sub
Effects of Executing Macro Example to Create Named Range
The following image illustrates the results of executing the macro example. The cell range containing cells A5 to C10 is named as “namedRange”.
#2: Create Named Range with Worksheet Scope
VBA Code to Create Named Range with Worksheet Scope
To create a named range with worksheet scope using VBA, use a statement with the following structure:
Worksheet.Names.Add Name:=RangeName, RefersTo:=NamedRangeWorksheet
Process Followed by VBA to Create Named Range with Worksheet Scope
VBA Statement Explanation
- Item: Worksheet.
- VBA Construct: Worksheet object.
- Description: You can use VBA constructs such as the ActiveSheet property or the Workbook.Worksheets property to return a Worksheet object representing the worksheet to which you want to limit the scope of the named range.
- Item: Names.
- VBA Construct: Worksheet.Names property.
- Description: The Worksheet.Names property returns a Names collection representing all the names in Worksheet.
- Item: Add.
- VBA Construct: Names.Add method.
- Description: The Names.Add method sets a new name for a cell range.
- Item: Name:=RangeName.
- VBA Construct: Name parameter of the Names.Add method.
- Description: The Name parameter of the Names.Add method allows you to specify the name of the named range you specify. Consider the following usual requirements when specifying RangeName:
- RangeName must start with a letter or underscore.
- Certain characters aren’t allowed. For example, RangeName can’t include spaces.
- RangeName can’t conflict with an existing name.
- RangeName can’t be formatted as a cell reference. For example, names such as “ABC1” aren’t allowed.
- If you want to specify the Name parameter using localized text, (i) work with the NameLocal parameter of the Names.Add method, and (ii) omit the Name parameter of the Names.Add method.
If you explicitly declare a variable to represent RangeName, use the String data type.
- Item: RefersTo:=NamedRangeWorksheet.
- VBA Construct: RefersTo parameter of the Names.Add method.
- Description: The RefersTo parameter of the Names.Add method allows you to specify the cell range to which the name refers to. The RefersTo parameter is of the Variant data type. Therefore, you commonly specify NamedRangeWorksheet as one of the following:
- A Range object.
- A string that uses the A1-style notation.
When working with the Names.Add method, you can also specify the cell range to which the name refers to using the following parameters.
- RefersToLocal: Allows you to specify the cell range in localized text using the A1-style notation.
- RefersToR1C1: Allows you to specify the cell range in R1C1-style notation.
- RefersToR1C1Local: Allows you to specify the cell range in localized text using the R1C1-style notation.
When working with one of the 4 parameters I refer to (RefersTo, RefersToLocal, RefersToR1C1, or RefersToR1C1Local), specify that single parameter and omit the others.
If you explicitly declare a variable to represent NamedRangeWorksheet, use the Range object data type (if specifying NamedRangeWorksheet as a Range object) or the String data type (if specifying NamedRangeWorksheet as a string).
Macro Example to Create Named Range with Worksheet Scope
The following macro example creates a named range with worksheet scope (myWorksheet) by setting the name of the cell range composed of cells D5 to F10 (myNamedRangeWorksheet) of the Named Range worksheet (myWorksheet) to “namedRangeWorksheet” (myRangeName).
Sub createNamedRangeWorksheetScope() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/vba-create-named-range/ 'declare object variables to hold references to worksheet containing cell range, and cell range itself Dim myWorksheet As Worksheet Dim myNamedRangeWorksheet As Range 'declare variable to hold defined name Dim myRangeName As String 'identify worksheet containing cell range, and cell range itself Set myWorksheet = ThisWorkbook.Worksheets("Named Range") Set myNamedRangeWorksheet = myWorksheet.Range("D5:F10") 'specify defined name myRangeName = "namedRangeWorksheet" 'create named range with worksheet scope. Defined name and cell range are as specified myWorksheet.Names.Add Name:=myRangeName, RefersTo:=myNamedRangeWorksheet End Sub
Effects of Executing Macro Example to Create Named Range with Worksheet Scope
The following image illustrates the results of executing the macro example. The cell range containing cells D5 to F10 is named as “namedRangeWorksheet”.
#3: Create Named Range from Selection
VBA Code to Create Named Range from Selection
To create a named range from the current selection using VBA, use a statement with the following structure:
Scope.Names.Add Name:=RangeName, RefersTo:=Selection
Process Followed by VBA to Create Named Range from Selection
VBA Statement Explanation from Selection
- Item: Scope.
- VBA Construct: Workbook or Worksheet object.
- Description: Scope of the named range you create. The scope of a named range can generally be 1 of the following:
- Workbook. In this case, Scope must represent a Workbook object. For these purposes, you can use VBA constructs such as the ActiveWorkbook property, the ThisWorkbook property or the Application.Workbooks property.
- Worksheet. In this case, Scope must represent a Worksheet object. For these purposes, you can use VBA constructs such as the ActiveSheet property.
For a more detailed description of how to create a named range with worksheet scope, please refer to the appropriate section above.
- Item: Names.
- VBA Construct: Workbook.Names property (when Scope is a Workbook object) or Worksheet.Names property (when scope is a Worksheet object).
- Description: The Names property returns a Names collection representing all the names in the workbook (when Scope is a Workbook object) or worksheet (when Scope is a Worksheet object) represented by Scope. The Names collection returned by the Workbook.Names property includes worksheet-specific names.
- Item: Add.
- VBA Construct: Names.Add method.
- Description: The Names.Add method sets a new name for a cell range.
- Item: Name:=RangeName.
- VBA Construct: Name parameter of the Names.Add method.
- Description: The Name parameter of the Names.Add method allows you to specify the name of the named range you specify. Consider the following usual requirements when specifying RangeName:
- RangeName must start with a letter or underscore.
- Certain characters aren’t allowed. For example, RangeName can’t include spaces.
- RangeName can’t conflict with an existing name.
- RangeName can’t be formatted as a cell reference. For example, names such as “ABC1” aren’t allowed.
- If you want to specify the Name parameter using localized text, (i) work with the NameLocal parameter of the Names.Add method, and (ii) omit the Name parameter of the Names.Add method.
If you explicitly declare a variable to represent RangeName, use the String data type.
- Item: RefersTo:=Selection.
- VBA Construct: RefersTo parameter of the Names.Add method and Selection property.
- Description: The RefersTo parameter of the Names.Add method allows you to specify the cell range to which the name refers to.
The Selection property returns a Range object representing the current selected cells. This is the cell range you name.
Macro Example to Create Named Range from Selection
The following macro example creates a named range with workbook scope (ThisWorkbook) by setting the name of the selection (Selection) to “namedRangeFromSelection” (myRangeName).
Sub createNamedRangeFromSelection() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/vba-create-named-range/ 'declare variable to hold defined name Dim myRangeName As String 'specify defined name myRangeName = "namedRangeFromSelection" 'create named range with workbook scope. Defined name is as specified. Cell range is the selection ThisWorkbook.Names.Add Name:=myRangeName, RefersTo:=Selection End Sub
Effects of Executing Macro Example to Create Named Range from Selection
The following image illustrates the results of executing the macro example. The current selection, containing cells G5 to I10 is named as “namedRangeFromSelection”.
#4: Create Named Range (Dynamic)
VBA Code to Create Named Range (Dynamic)
To create a named range from a dynamic range (where the number of the last row and last column changes) with VBA, use a macro with the following statement structure:
Dim LastRow As Long Dim LastColumn As Long Dim NamedRangeDynamic As Range With Worksheet.Cells LastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row LastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column Set NamedRangeDynamic = .Range(.Cells(1, 1), .Cells(LastRow, LastColumn)) End With Scope.Names.Add Name:=RangeName, RefersTo:=NamedRangeDynamic
Process Followed by VBA to Create Named Range (Dynamic)
VBA Statement Explanation (Dynamic)
Line #1: Dim LastRow As Long
- Item: Dim LastRow as Long.
- VBA Construct: Dim statement.
- Description: Declares the LastRow variable as of the Long data type.
LastRow holds the number of the last row with data in the worksheet containing the cell range you name (Worksheet).
Line #2: Dim LastColumn As Long
- Item: Dim LastColumn as Long.
- VBA Construct: Dim statement.
- Description: Declares the LastColumn variable as of the Long data type.
LastColumn holds the number of the last column with data in the worksheet containing the cell range you name (Worksheet).
Line #3: Dim NamedRangeDynamic As Range
- Item: Dim NamedRangeDynamic As Range.
- VBA Construct: Dim statement.
- Description: Declares the NamedRangeDynamic variable as of the Range object data type.
NamedRangeDynamic represents the cell range you name.
Lines #4 and #8:With Worksheet.Cells | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement are executed on the Range object returned by Worksheet.Cells.
- Item: Worksheet.
- VBA Construct: Worksheet object.
- Description: Represents the worksheet containing the cell range you name. If you explicitly declare an object variable to represent Worksheet, use the Worksheet object data type.
- Item: Cells.
- VBA Construct: Worksheet.Cells property.
- Description: Returns a Range object representing all the cells in Worksheet.
Line #5: LastRow = .Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
- Item: LastRow.
- VBA Construct: Variable of the long data type.
- Description: LastRow holds the number of the last row with data in Worksheet.
- Item: =.
- VBA Construct: Assignment operator.
- Description: Assigns the row number returned by the Range.Row property to the LastRow variable.
- Item: Find.
- VBA Construct: Range.Find method.
- Description: Returns a Range object representing the first cell where the information specified by the parameters of the Range.Find method (What, LookIn, LookAt, SearchOrder and SearchDirection) is found. Within this macro structure, this Range object represents the last cell with data in the last row with data in Worksheet.
- Item: What:=”*”.
- VBA Construct: What parameter of the Range.Find method.
- Description: Specifies the data the Range.Find method searches for. The asterisk (*) is a wildcard and, therefore, the Range.Find method searches for any character sequence.
- Item: LookIn:=xlFormulas.
- VBA Construct: LookIn parameter of the Range.Find method.
- Description: Specifies that the Range.Find method looks in formulas (xlFormulas).
- Item: LookAt:=xlPart.
- VBA Construct: LookAt parameter of the Range.Find method.
- Description: Specifies that the Range.Find method looks at (and matches) a part (xlPart) of the search data.
- Item: SearchOrder:=xlByRows.
- VBA Construct: SearchOrder parameter of the Range.Find method.
- Description: Specifies that the Range.Find method searches by rows (xlByRows).
- Item: SearchDirection:=xlPrevious.
- VBA Construct: SearchDirection parameter of the Range.Find method.
- Description: Specifies that the Range.Find method searches for the previous match (xlPrevious).
- Item: Row.
- VBA Construct: Range.Row property.
- Description: Returns the row number of the Range object returned by the Range.Find method. Within this macro structure, this row number corresponds to the last row with data in Worksheet.
Line #6: LastColumn = .Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
- Item: LastColumn.
- VBA Construct: Variable of the long data type.
- Description: LastColumn holds the number of the last column with data in Worksheet.
- Item: =.
- VBA Construct: Assignment operator.
- Description: Assigns the column number returned by the Range.Column property to the LastColumn variable.
- Item: Find.
- VBA Construct: Range.Find method.
- Description: Returns a Range object representing the first cell where the information specified by the parameters of the Range.Find method (What, LookIn, LookAt, SearchOrder and SearchDirection) is found. Within this macro structure, this Range object represents the last cell with data in the last column with data in Worksheet.
- Item: What:=”*”.
- VBA Construct: What parameter of the Range.Find method.
- Description: Specifies the data the Range.Find method searches for. The asterisk (*) is a wildcard and, therefore, the Range.Find method searches for any character sequence.
- Item: LookIn:=xlFormulas.
- VBA Construct: LookIn parameter of the Range.Find method.
- Description: Specifies that the Range.Find method looks in formulas (xlFormulas).
- Item: LookAt:=xlPart.
- VBA Construct: LookAt parameter of the Range.Find method.
- Description: Specifies that the Range.Find method looks at (and matches) a part (xlPart) of the search data.
- Item: SearchOrder:=xlByColumns.
- VBA Construct: SearchOrder parameter of the Range.Find method.
- Description: Specifies that the Range.Find method searches by columns (xlByColumns).
- Item: SearchDirection:=xlPrevious.
- VBA Construct: SearchDirection parameter of the Range.Find method.
- Description: Specifies that the Range.Find method searches for the previous match (xlPrevious).
- Item: Column.
- VBA Construct: Range.Column property.
- Description: Returns the column number of the Range object returned by the Range.Find method. Within this macro structure, this column number corresponds to the last column with data in Worksheet.
Line #7: Set NamedRangeDynamic = .Range(.Cells(1, 1), .Cells(LastRow, LastColumn))
- Item: NamedRangeDynamic.
- VBA Construct: Object variable of the Range object data type.
- Description: NamedRangeDynamic represents the cell range you name.
- Item: =.
- VBA Construct: Assignment operator.
- Description: Assigns the Range object returned by the Range.Range property to the NamedRangeDynamic object variable.
- Item: Range.
- VBA Construct: Range.Range property.
- Description: Returns a Range object representing the cell range you name. Within this macro structure, the Range property is applied to the Range object returned by the Worksheet.Cells property in the opening statement of the With… End With statement.
- Item: Cells(1, 1).
- VBA Construct: Cells1 parameter of the Range.Range property, Range.Cells property and Range.Item property.
- Description: The Cells1 parameter of the Range.Range property specifies the cell in the upper-left corner of the cell range. Within this macro structure, Cells1 is the Range object returned by the Range.Cells property.
The Range.Cells property returns all the cells within the cell range represented by the Range object returned by the Worksheet.Cells property in the opening statement of the With… End With statement. The Range.Item property is the default property and returns a Range object representing the cell on the first row and first column (Cells(1, 1)) of the cell range it works with.
Since the Worksheet.Cells property in the opening statement of the With… End With statement returns all the cells in Worksheet, this is cell A1 of Worksheet.
- Item: Cells(LastRow, LastColumn).
- VBA Construct: Cells2 parameter of the Range.Range property, Range.Cells property and Range.Item property.
- Description: The Cells2 parameter of the Range.Range property specifies the cells in the lower-right corner of the cell range. Within this macro structure, Cells2 is the Range object returned by the Range.Cells property.
The Range.Cells property returns all the cells within the cell range represented by the Range object returned by the Worksheet.Cells property in the opening statement of the With… End With statement (line #4 above). The Range.Item property is the default property and returns a Range object representing the cell located at the intersection of LastRow and LastColumn.
Since the Worksheet.Cells property in the opening statement of the With… End With statement returns all the cells in Worksheet, this is the cell located at the intersection of the last row and the last column (or the last cell with data) within Worksheet.
Line #9: Scope.Names.Add Name:=RangeName, RefersTo:=NamedRangeDynamic
- Item: Scope.
- VBA Construct: Workbook or Worksheet object.
- Description: Scope of the named range you create. The scope of a named range can generally be 1 of the following:
- Workbook. In this case, Scope must represent a Workbook object. For these purposes, you can use VBA constructs such as the ActiveWorkbook property, the ThisWorkbook property or the Application.Workbooks property.
- Worksheet. In this case, Scope must represent a Worksheet object. For these purposes, you can use VBA constructs such as the ActiveSheet property or the Workbook.Worksheets property.
For a more detailed description of how to create a named range with worksheet scope, please refer to the appropriate section above.
- Item: Names.
- VBA Construct: Workbook.Names property (when Scope is a Workbook object) or Worksheet.Names property (when scope is a Worksheet object).
- Description: The Names property returns a Names collection representing all the names in the workbook (when Scope is a Workbook object) or worksheet (when Scope is a Worksheet object) represented by Scope. The Names collection returned by the Workbook.Names property includes worksheet-specific names.
- Item: Add.
- VBA Construct: Names.Add method.
- Description: The Names.Add method sets a new name for a cell range.
- Item: Name:=RangeName.
- VBA Construct: Name parameter of the Names.Add method.
- Description: The Name parameter of the Names.Add method allows you to specify the name of the named range you specify. Consider the following usual requirements when specifying RangeName:
- RangeName must start with a letter or underscore.
- Certain characters aren’t allowed. For example, RangeName can’t include spaces.
- RangeName can’t conflict with an existing name.
- RangeName can’t be formatted as a cell reference. For example, names such as “ABC1” aren’t allowed.
- If you want to specify the Name parameter using localized text, (i) work with the NameLocal parameter of the Names.Add method, and (ii) omit the Name parameter of the Names.Add method.
If you explicitly declare a variable to represent RangeName, use the String data type.
- Item: RefersTo:=NamedRangeDynamic.
- VBA Construct: RefersTo parameter of the Names.Add method.
- Description: The RefersTo parameter of the Names.Add method allows you to specify the cell range to which the name refers to.
NamedRangeDynamic is an object variable of the Range object data type representing the cell range you name.
Macro Example to Create Named Range (Dynamic)
The following macro example creates a named range with workbook scope (ThisWorkbook) by dynamically identifying the last row (myLastRow) and last column (myLastColumn) with data in the Named Range worksheet (myWorksheet) and setting its name to “namedRangeDynamic” (myRangeName). In this case, the first cell of namedRangeDynamic is A11 (intersection of myFirstRow and myFirstColumn).
Sub createNamedRangeDynamic() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/vba-create-named-range/ 'declare object variable to hold reference to worksheet containing cell range Dim myWorksheet As Worksheet 'declare variables to hold row and column numbers that define named cell range (dynamic) Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long 'declare object variable to hold reference to cell range Dim myNamedRangeDynamic As Range 'declare variable to hold defined name Dim myRangeName As String 'identify worksheet containing cell range Set myWorksheet = ThisWorkbook.Worksheets("Named Range") 'identify first row and first column of cell range myFirstRow = 11 myFirstColumn = 1 'specify defined name myRangeName = "namedRangeDynamic" With myWorksheet.Cells 'find last row and last column of source data cell range myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column 'specify cell range Set myNamedRangeDynamic = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) End With 'create named range with workbook scope. Defined name is as specified. Cell range is as identified, with the last row and column being dynamically determined ThisWorkbook.Names.Add Name:=myRangeName, RefersTo:=myNamedRangeDynamic End Sub
Effects of Executing Macro Example to Create Named Range (Dynamic)
The following image illustrates the results of executing the macro example. The cell range containing data (Data) (cells A11 to I20) is named as “namedRangeDynamic”.
References to VBA Constructs Used in this VBA Tutorial
Use the following links to visit the appropriate webpage in the Microsoft Developer Network:
- Specify the scope of a named range (workbook or worksheet):
- Workbook object.
- Workbook.Names property.
- Application.ActiveWorkbook property.
- Application.ThisWorkbook property.
- Application.Workbooks property.
- Worksheet object.
- Worksheet.Names property.
- Application.ActiveSheet property.
- Workbook.Worksheets property.
- Identify the cell range to name:
- Range object.
- Worksheet.Range property.
- Worksheet.Cells property.
- Application.Selection property.
- Range.Range property.
- Range.Cells property.
- Range.Item property.
- Identify the last row or column with data in a worksheet:
- Range.Find method.
- Range.Row property.
- Range.Column property.
- Set a new named range:
- Names collection.
- Name object.
- Names.Add method.
- Range.Name property.
- Work with variables and data types:
- Dim statement.
- Set statement.
- Data types:
- String data type.
- Long data type.
Excel is your ultimate productivity tool. Learn how to create Named Ranges in Excel using VBA and find tips to save time when working with data and formulas.
Microsoft Excel is a powerful software application that you can use to create, track, and analyze data. In addition to the standard features of Excel, you can also create VBA macros to automate certain tasks.
Are you looking to learn about creating Named Ranges and using VBA macros in Excel? If so, you have come to the right place. In this blog post, we will discuss how to create Named Ranges in Excel using VBA.
We will also provide some examples of how you can use Named Ranges in your own work. Let’s get started!
What Is a Named Range in Microsoft Excel?
Using a named range instead of a column/row reference, you can refer to a cell or group of cells with a custom name. The ability to specify the data inside your cells is a huge benefit of using Named Ranges.
Here’s a quick example of how you can use Named Ranges to tell if the shipping costs are charged with the product price:
- = (B7 + B5 * C4) * (1 + A3)
- =(ShippingCharge + ProductPrice * Quantity) * (1 + TaxRate)
Option number two, as you can see, gives you an immediate indication of whether the price of the products includes shipping expenses. This makes it simple for the user to comprehend how the formula works without having to waste time looking through cells to figure out what is what.
How To Use Named Ranges in Excel?
As a financial analyst, you might be expected to experiment with various rates. Anything from a tax rate to a projected inflation rate might be used as an example. You can use Named Ranges to organize variables that are either modified seldom (such as Month or Year) or will remain static for a long period (like the inflation rate).
Here’s a list of common names you may use often when working with Named Ranges in Excel:
- ReportDate
- Year
- Month
- FcstID
- TaxRate
- RawData
These are only some of the possibilities — you can name a range of anything you want that adheres to Excel’s rules for Named Ranges.
Create Unique Names
Creating a Named Range is a breeze. All you have to do now is select the cell(s) you wish to refer to and type a name in the Name Box.
Because your name cannot contain any spaces, you must capitalize the first letter of each new word or use an underscore (_) to separate terms. To finalize the establishment of the Named Range, press the ENTER key after you’ve done typing the name.
Note: Any Named Range established with the Name Box has a Workbook scope. This means that any worksheet in your Excel file can access the named range.
Creating Names Using the Name Manager
You can change and create new Named Ranges in the Name Manager (Formulas tab > Defined Names group > Name Manager button) if you wish to customize your Named Ranges even more.
You should be aware that the Name Manager allows you to:
- Change the name of a Named Range that already exists,
- Make a reference formula change,
- Define the scope of which worksheets the name can be accessed.
Now that you understand what a named range is and how to create one, let’s look at some practical examples of how you can use them in your work.
Practical Examples of How To Use Named Ranges
Example 1: Creating a Dynamic Range
A dynamic range is a named range that automatically adjusts to include new data that is added to the worksheet. This is a great way to save time when your data changes often.
Example 2: Creating a 3D Range
A 3D range is a named range that refers to data in multiple worksheets. This can be a great time-saver if you work with large amounts of data that are organized in a similar fashion across multiple worksheets.
Example 3: Creating a Named Array
A named array is a type of dynamic range that refers to an array of values. This can be a great way to reference data that is organized in a table format.
Automate Named Ranges With VBA Macros
Now that we’ve gone over a quick review of Named Ranges, let’s look at some VBA macros that can help you automate your use of them.
Add a Named Range
The VBA code below demonstrates how to construct various sorts of Named Ranges.
Sub NameRange_Add()
‘PURPOSE: Various ways to create a Named Range
‘SOURCE: SoftwareKeep.com
Dim cell As Range
Dim rng As Range
Dim RangeName As String
Dim CellName As String
‘Single Cell Reference (Workbook Scope)
RangeName = «Price»
CellName = «D7»
Set cell = Worksheets(«Sheet1»).Range(CellName)
ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell
‘Single Cell Reference (Worksheet Scope)
RangeName = «Year»
CellName = «A2»
Set cell = Worksheets(«Sheet1»).Range(CellName)
Worksheets(«Sheet1»).Names.Add Name:=RangeName, RefersTo:=cell
‘Range of Cells Reference (Workbook Scope)
RangeName = «myData»
CellName = «F9:J18»
Set cell = Worksheets(«Sheet1»).Range(CellName)
ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell
‘Secret Named Range (doesn’t show up in Name Manager)
RangeName = «Username»
CellName = «L45»
Set cell = Worksheets(«Sheet1»).Range(CellName)
ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell, Visible:=False
End Sub
Loop Through Named Ranges
The next VBA macro code demonstrates how to cycle through your spreadsheet’s Named Ranges.
Sub NamedRange_Loop()
‘PURPOSE: Delete all Named Ranges in the Active Workbook
‘SOURCE: SoftwareKeep.com
Dim nm As Name
‘Loop through each named range in workbook
For Each nm In ActiveWorkbook.Names
Debug.Print nm.Name, nm.RefersTo
Next nm
‘Loop through each named range scoped to a specific worksheet
For Each nm In Worksheets(«Sheet1»).Names
Debug.Print nm.Name, nm.RefersTo
Next nm
End Sub
Delete All Named Ranges
This VBA function will help you clean out a large chunk of Named Ranges in Excel that you no longer need in your project.
Sub NamedRange_DeleteAll()
‘PURPOSE: Delete all Named Ranges in the ActiveWorkbook (Print Areas optional)
‘SOURCE: SoftwareKeep.com
Dim nm As Name
Dim DeleteCount As Long
‘Delete PrintAreas as well?
UserAnswer = MsgBox(«Do you want to skip over Print Areas?», vbYesNoCancel)
If UserAnswer = vbYes Then SkipPrintAreas = True
If UserAnswer = vbCancel Then Exit Sub
‘Error Handler in case Delete Function Errors out
On Error GoTo Skip
‘Loop through each name and delete
For Each nm In ActiveWorkbook.Names
If SkipPrintAreas = True And Right(nm.Name, 10) = «Print_Area» Then GoTo Skip
‘Error Handler in case Delete Function Errors out
On Error GoTo Skip
‘Delete Named Range
nm.Delete
DeleteCount = DeleteCount + 1
Skip:
‘Reset Error Handler
On Error GoTo 0
Next
‘Report Result
If DeleteCount = 1 Then
MsgBox «[1] name was removed from this workbook.»
Else
MsgBox «[» & DeleteCount & «] names were removed from this workbook.»
End If
End Sub
Delete Named Ranges With Errors
Only Named Ranges with faults will be deleted with this VBA code. These problems might be triggered by the deletion of worksheets or rows/columns.
Sub NamedRange_DeleteErrors()
‘PURPOSE: Delete all Named Ranges with #REF error in the ActiveWorkbook
‘SOURCE: SoftwareKeep.com
Dim nm As Name
Dim DeleteCount As Long
‘Loop through each name and delete
For Each nm In ActiveWorkbook.Names
If InStr(1, nm.RefersTo, «#REF!») > 0 Then
‘Error Handler in case Delete Function Errors out
On Error GoTo Skip
‘Delete Named Range
nm.Delete
DeleteCount = DeleteCount + 1
End If
Skip:
‘Reset Error Handler
On Error GoTo 0
Next
‘Report Result
If DeleteCount = 1 Then
MsgBox «[1] errorant name was removed from this workbook.»
Else
MsgBox «[» & DeleteCount & «] errorant names were removed from this workbook.»
End If
End Sub
TL;DR
- Named ranges are a great way to organize your data in Excel.
- You can use them to create dynamic ranges, 3D ranges, and named arrays.
- You can also automate your use of Named Ranges with VBA macros.
Conclusion
Excel is an amazing tool that can make even the most mundane tasks exciting to complete with vast automation features. If you want to make your life easier, learning how to work with advanced tools like Named Ranges with VBA is a great way to start.
We hope this article has helped you learn a little bit more about how to use Named Ranges in Excel. As always, if you have any questions, feel free to leave us a comment below!
Thank you for reading.
One More Thing
Looking for more tips? Check out our other guides in our Blog or visit our Help Center for a wealth of information on how to troubleshoot various issues.
Sign up for our newsletter and access our blog posts, promotions, and discount codes early. Plus, you’ll be the first to know about our latest guides, deals, and other exciting updates!
Recommended Articles
» How To Add and Remove Leading Zeros in Excel
» How To Use “If Cell Contains” Formulas in Excel
» How To Lock and Unlock the Scroll Lock in Excel?
Feel free to reach out with questions or requests you’d like us to cover.