Code: Create a Dynamic Range in Excel VBA
Sub CreateDynamicRange()
Dim ws As Worksheet
Dim lastRow As Long
Dim lastCol As Long
Dim rng As Range
Dim rngName As String
' Set the worksheet where the dynamic range is defined
Set ws = ThisWorkbook.Sheets("Sheet1")
' Find the last used row in the worksheet (considering column A)
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
' Find the last used column in the worksheet (considering row 1)
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
' Define the dynamic range
Set rng = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol))
' Name the range dynamically
rngName = "DynamicRange"
On Error Resume Next
ws.Names(rngName).Delete ' Remove existing named range if any
On Error GoTo 0
ws.Names.Add Name:=rngName, RefersTo:=rng
' Confirm the range in a message box
MsgBox "Dynamic range '" & rngName & "' is created successfully from " & _
rng.Address & " in " & ws.Name, vbInformation, "Range Created
End Sub
Detailed Explanation
- Declaring Variables
- ws → This is the worksheet object that refers to « Sheet1 ».
- lastRow → This will store the last used row in column A.
- lastCol → This will store the last used column in row 1.
- rng → This represents the dynamically determined range.
- rngName → This holds the name of the named range.
- Identifying the Last Used Row and Column
- ws.Cells(ws.Rows.Count, 1).End(xlUp).Row → Finds the last non-empty cell in column A.
- ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column → Finds the last non-empty cell in row 1.
- Defining the Dynamic Range
- The range is set using:
- Set rng = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol))
This ensures the range starts from A1 and extends dynamically based on data.
- Creating a Named Range
- ws.Names(rngName).Delete → Removes any existing named range with the same name.
- ws.Names.Add Name:=rngName, RefersTo:=rng → Assigns a named range « DynamicRange ».
- Confirmation Message
- MsgBox displays the created range and confirms successful execution.
Use Cases and Applications
- Auto-Updating Charts
- This range can be used in charts to automatically adjust to new data.
- Pivot Tables
- Setting this dynamic range as the data source in pivot tables ensures it updates automatically.
- Data Validation and Dropdowns
- Can be used as a source for dynamic dropdown lists in Excel.
- Conditional Formatting
- Applying rules to dynamic datasets without manually adjusting ranges.