To create a dynamic named range with VBA, define a workbook name whose formula adjusts to the current data, then update that formula when needed. For example, a name called SalesData can refer to all populated cells in column A from A2 downward, rather than a fixed range that stops growing when new rows are added.
What a dynamic named range does
An Excel named range gives a readable name to a cell or range. A dynamic named range changes its referenced cells as data is added or removed, which can help formulas, charts, validation lists, and VBA procedures work with a changing dataset. VBA can create or revise the name, but the name’s underlying formula determines whether it expands automatically.
There are two useful approaches:
- Use an Excel Table: Tables expand when you enter data directly below them, and structured references adapt automatically. This is usually the simplest option for growing datasets.
- Use a defined name with a formula: A name can refer to a range whose size is calculated from the data. VBA can create that name and change its definition when your layout or rules require it.
A name created by VBA is not necessarily dynamic. If VBA assigns it to $A$2:$A$20, it remains a fixed reference unless code changes it or its definition uses a dynamic formula.
Create a dynamic name with VBA
This example creates a workbook-level name, SalesData, for nonblank cells in column A beginning at A2. It assumes row 1 is a heading and that the data is contiguous: there are no blank cells between the first and last entries. The formula uses INDEX and COUNTA so the name’s endpoint changes as the number of nonblank cells changes.
Sub CreateSalesDataName()
Dim ws As Worksheet
Dim refersToFormula As String
Set ws = ThisWorkbook.Worksheets("Data")
' Count entries in A2:A1048576 and return the matching endpoint.
refersToFormula = "=Data!$A$2:INDEX(Data!$A:$A,COUNTA(Data!$A:$A))"
' Replace the workbook-level name if it already exists.
On Error Resume Next
ThisWorkbook.Names("SalesData").Delete
On Error GoTo 0
ThisWorkbook.Names.Add Name:="SalesData", _
RefersTo:=refersToFormula
End Sub
In this setup, if A1 contains a heading and A2:A5 contain four entries, COUNTA counts five nonblank cells in column A. The final reference is A2:A5. If a fifth entry is added in A6, the endpoint becomes A6. The formula assumes the heading and entries are all nonblank and there are no unrelated nonblank cells elsewhere in column A; otherwise, the count can produce an incorrect endpoint.
Change Data to the actual worksheet name. Sheet names containing spaces need single quotes in a worksheet reference, for example 'Monthly Data'!$A$2. When constructing more complex references, verify the exact formula stored in Name Manager.
Understand the formula and its limits
COUNTA counts nonempty cells; INDEX returns a reference to a cell at a specified position. Together, they let the defined name end at a row determined by the count. This is a familiar technique, but it is sensitive to data layout.
- If there are blanks inside the list,
COUNTAcounts entries but not the last used row. The resulting endpoint may stop too early. - If other content appears in column A below the list, it is counted too, so the name may include unwanted cells.
- If formulas returning an empty string are present, Excel’s counting behavior may not match the intended meaning of “last data row.” Test the specific layout.
- If the list may contain gaps or unrelated content, use an Excel Table or write VBA that finds the last used row according to a clearly defined column and rule.
For example, code can find the last nonempty cell in column A with Cells(Rows.Count, 1).End(xlUp).Row. That approach identifies the last occupied row, even if earlier rows have gaps. It still needs a policy for an empty list and for unrelated data below the list; “last used row” is not automatically the same as “last row in this dataset.”
Update a name from VBA
If the range should be fixed between macro runs, VBA can calculate its current last row and assign a direct reference. This is not self-expanding after the macro finishes; run the procedure again after the data changes.
Sub UpdateSalesDataName()
Dim ws As Worksheet
Dim lastRow As Long
Dim target As Range
Set ws = ThisWorkbook.Worksheets("Data")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
' Do not include the heading when there are no data rows.
If lastRow < 2 Then Exit Sub
Set target = ws.Range("A2:A" & lastRow)
On Error Resume Next
ThisWorkbook.Names("SalesData").Delete
On Error GoTo 0
ThisWorkbook.Names.Add Name:="SalesData", _
RefersTo:="=" & target.Address(External:=True)
End Sub
The resulting name refers to the current cells from A2 to the last occupied row in column A. The External:=True address includes the worksheet and workbook context, helping Excel resolve the reference. This procedure exits without replacing the name when no data row is found; adjust that behavior if an empty range should instead remove the name.
Choose between a name, a table, and VBA
For most new workbooks, an Excel Table is the most maintainable choice. Select the data and use Insert > Table (or press Ctrl+T on Windows), confirming whether the range has headers. Tables expand as rows are added, and formulas can refer to table columns by name. On Mac, use the Table command on the Insert tab; keyboard shortcuts can differ by Excel version and keyboard settings.
Choose a formula-based defined name when a feature specifically needs a named range, or when the range must follow a rule that a table does not express conveniently. Choose VBA when the name must be created as part of workbook setup, refreshed by a macro, or customized based on workbook state. A macro is not required simply to make a name dynamic.
Workbook-level names are available throughout the workbook. Worksheet-level names are scoped to a particular sheet and can share a name with a name on another sheet. VBA’s ThisWorkbook.Names collection addresses names in the workbook containing the macro; use the appropriate worksheet’s Names collection when a sheet-scoped name is intended.
Inspect, test, and troubleshoot
In Microsoft 365 for Windows, open Formulas > Name Manager to review a name’s scope and its Refers to formula. Select the name to see its current reference. In Excel for Mac, the Name Manager is also available from the Formulas tab, though the ribbon layout may vary. To test the VBA name, enter a few sample rows, run the macro, and check whether the reference includes exactly the intended cells.
- “Subscript out of range”: Check that the worksheet name in the code matches the tab name exactly.
- The name does not grow: A direct address is fixed. Use a formula-based name or rerun the updating macro.
- The name includes too much: Check for stray values below the list and confirm the column used to count or locate its endpoint.
- The name is not visible everywhere: Check whether it has workbook scope or worksheet scope.
- The name refers to an invalid range: Inspect spelling, quotes around sheet names, and the formula in Name Manager.
To run the sample, press Alt+F11 on Windows to open the Visual Basic Editor, insert a standard module, and paste the procedure there. On Mac, open the Visual Basic Editor from Tools > Macro > Visual Basic Editor or use the Developer tab if available; shortcuts vary by keyboard and Excel version. Save macro-enabled workbooks as .xlsm if they need to retain VBA. Save a copy before running a macro: VBA changes cannot be undone with Ctrl+Z.
Frequently Asked Questions
Can a VBA-created named range expand without running the macro again?
Yes, if VBA defines the name using a formula that recalculates based on the data, as in the INDEX/COUNTA example. A name assigned a fixed address only changes when code updates it.
Is a dynamic named range the same as an Excel Table?
No. Both can adapt to added data, but a Table is a built-in structured data feature, while a dynamic named range is a defined name whose reference is calculated or changed. Tables are generally easier to maintain for ordinary lists.
Why does COUNTA give the wrong last row?COUNTA measures how many cells are nonblank, not the row number of the last entry. Gaps, extra values, or formulas can make that count differ from the endpoint you expect.
Can I use the named range in a chart or formula?
Usually, yes. A workbook-level name can be used in formulas and, where supported by the chart setup, as a series reference. Confirm the name’s scope and test the chart after adding rows, since chart-series behavior can depend on how the chart was created.
Do I need to enable macros for a formula-based name to remain dynamic?
No. Once the name exists, Excel can recalculate its defined formula without running VBA. Macros are needed to create or change the name through code, not to recalculate a valid formula-based name.
Related
- Dynamic Name Range in Excel: How to Create One
- Excel Data Validation List From a Named Range
- Adjust a Named Range in Excel
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA Outlook: How to Create a Contact GroupIn classic Outlook for Windows, VBA can create a contact group by making an Outlook DistListItem, adding resolved…
- Excel VBA Color Codes: RGB, Hex, and ColorIndex GuideIn Excel VBA, set a cell’s fill color with Range("A1").Interior.Color = RGB(255, 0, 0); the three numbers are…
- Case in VBA: Select, Activate, and Workbooks ExplainedIn VBA, “Case” most commonly refers to the Select Case statement, a conditional branching structure that runs different…
- VBA InputBox Default Value: Set and Use ItIn VBA, set an InputBox’s default value with its third argument: InputBox(prompt, title, default). For example, InputBox("Enter a…
- Free Macro Recorder for Windows 11: Best OptionsYes. Windows 11 users can record and replay desktop actions for free with Microsoft Power Automate for desktop,…
- VBA Range.Resize: Change a Range’s Dimensions in ExcelIn Excel VBA, use the Resize property to return a range with a different number of rows or…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.