Mar 06 2024 11:44 AM - edited Mar 06 2024 03:15 PM
I have a workbook that uses a dynamic range to populate rows in a column on another worksheet. This works as it should but because of the formatting of the surrounding cells (color, etc.), what I really need is for the change to trigger a row to be added or removed in a specific range of cells.
I would create a new dynamic range on the worksheet where the new rows need to be added/removed. then I need to trigger a formula or macro where an change to the names in the first dynamic range cause a row to either be added or removed to in the second range of cells.
Edit: In the master worksheet I added a cell that contains the count of rows in the MembersCount dynamic range. I will be adding a range on the active worksheet called RowCount. RowCount should always be one more than MembersCount. So when the MembersCount changes I want to add a full row across or remove a full row at a specific location so that MembersCount is always one less than RowCount.
Example:
Mar 06 2024 09:31 PM
To achieve this functionality, you can use a Worksheet Change event macro in VBA.
With the information you have provided you could try out the following code.
Here's a step-by-step guide on how to set it up:
Vba code is untested, please backup your file.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim MembersCount As Range
Dim RowCount As Range
Dim ws As Worksheet
Dim LastRow As Long
Set ws = ThisWorkbook.Worksheets("YourWorksheetName") ' Change "YourWorksheetName" to the name of your worksheet
' Define the ranges
Set MembersCount = ws.Range("MembersCount") ' Change "MembersCount" to the address of your first dynamic range
Set RowCount = ws.Range("RowCount") ' Change "RowCount" to the address of your second dynamic range
' Check if the change occurred within the MembersCount range
If Not Intersect(Target, MembersCount) Is Nothing Then
Application.EnableEvents = False ' Disable events to prevent triggering the change event recursively
' Calculate the difference between MembersCount and RowCount
LastRow = RowCount.Row + RowCount.Rows.Count - 1
If MembersCount.Value > RowCount.Value Then
' Add rows above the specified cell
ws.Rows(LastRow).Resize(MembersCount.Value - RowCount.Value).Insert Shift:=xlDown
ElseIf MembersCount.Value < RowCount.Value Then
' Delete rows above the specified cell
ws.Rows(LastRow - (RowCount.Value - MembersCount.Value)).Resize(RowCount.Value - MembersCount.Value).Delete
End If
Application.EnableEvents = True ' Re-enable events
End If
End Sub
Hope this will help you.
Was the answer useful? Mark as best response and like it!
This will help all forum participants.
Mar 07 2024 03:28 AM