Finance

Charts

Statistics

Macros

Search

Create Dynamic Range Time Management Skills with Excel VBA

Step 1: Set Up Your Excel Worksheet

Before writing the VBA code, prepare your worksheet with time-related data. Assume that:

  • Column A contains task names.
  • Column B contains Start Time in hh:mm AM/PM format.
  • Column C contains End Time in hh:mm AM/PM format.
  • Column D will store Duration (calculated in hours).

Step 2: Write VBA Code

This VBA macro will dynamically define a named range for your time-related data and update it automatically when new data is entered.

Code:

Sub CreateDynamicTimeRange()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim timeRange As Range
    Dim namedRange As String   
    ' Set the worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1") ' Change "Sheet1" to your sheet name   
    ' Find the last row with data in Column A (Task Names)
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row 
    ' Define the range (Tasks + Time Data)
    Set timeRange = ws.Range("A2:D" & lastRow) ' Assuming headers are in Row 1   
    ' Name the range dynamically
    namedRange = "TimeManagementRange"   
    ' Delete existing named range if it exists
    On Error Resume Next
    ws.Names(namedRange).Delete
    On Error GoTo 0   
    ' Create new named range
    ws.Names.Add Name:=namedRange, RefersTo:=timeRange   
    ' Inform the user
    MsgBox "Dynamic Time Management Range Created: " & namedRange, vbInformation, "Success"  
End Sub

Step 3: Run the Code

  1. Open Excel and press ALT + F11 to open the VBA Editor.
  2. Click Insert > Module.
  3. Copy and paste the above VBA code into the module.
  4. Run the macro by pressing F5 or executing it from the Macro Menu.

Explanation:

  1. The macro selects the worksheet (Sheet1).
  2. It determines the last row in Column A (to ensure the range includes all time entries).
  3. It creates a dynamic range (TimeManagementRange) from column A to D.
  4. If the named range already exists, it deletes and recreates it.
  5. A message box confirms the creation of the dynamic range.

Output:

After running the macro, you can use the named range « TimeManagementRange » in formulas or data validation. The range updates automatically whenever you add new time data.

0 0 votes
Évaluation de l'article
S’abonner
Notification pour
guest
0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Online comments
Show all comments
Facebook
Twitter
LinkedIn
WhatsApp
Email
Print
0
We’d love to hear your thoughts — please leave a commentx