Objective:
This VBA code dynamically defines a named range based on data in an Excel sheet. The range expands automatically as new data is added.
VBA Code:
Sub CreateDynamicRange()
Dim ws As Worksheet
Dim lastRow As Long
Dim lastCol As Long
Dim rngName As String
Dim dynamicRange As Range
' Set worksheet where the dynamic range is created
Set ws = ThisWorkbook.Sheets("Sheet1")
' Define the range name
rngName = "DynamicData"
' Find the last row with data in column A (adjust as needed)
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
' Find the last column with data in row 1 (adjust as needed)
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
' Define the dynamic range
Set dynamicRange = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol))
' Delete existing named range if it exists
On Error Resume Next
ws.Names(rngName).Delete
On Error GoTo 0
' Create a new named range
ws.Names.Add Name:=rngName, RefersTo:=dynamicRange
' Notify user
MsgBox "Dynamic range '" & rngName & "' created successfully!", vbInformation, "Success"
End Sub
Detailed Explanation:
- Worksheet Selection:
Set ws = ThisWorkbook.Sheets(« Sheet1 »)
-
- The code sets the worksheet to « Sheet1 ». You can change this to any sheet where the data resides.
- Finding the Last Row:
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
-
- It looks for the last occupied cell in Column A by starting from the bottom of the worksheet (ws.Rows.Count) and moving up (xlUp).
3. Finding the Last Column:
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
-
- It finds the last occupied column in Row 1 by starting from the rightmost column (ws.Columns.Count) and moving left (xlToLeft).
4. Defining the Dynamic Range:
Set dynamicRange = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol))
-
- It creates a range from cell A1 (top-left) to the last detected row and column (bottom-right), ensuring all filled data is included.
5. Deleting Existing Named Range:
- On Error Resume Next
- Names(rngName).Delete
- On Error GoTo 0
-
- To avoid duplication, the script first deletes any existing named range with the same name.
6.Creating the Named Range:
- Names.Add Name:=rngName, RefersTo:=dynamicRange
-
- This assigns the dynamic range to a named range « DynamicData ».
7. User Notification:
- MsgBox « Dynamic range ‘ » & rngName & « ‘ created successfully! », vbInformation, « Success »
-
- Displays a confirmation message.
Usage:
- After running this macro, the named range « DynamicData » will adjust automatically whenever data expands or shrinks.
- You can use =DynamicData in formulas or PivotTables.