Ask Your Question
3

Does a VBA code exist that can add or delete rows in Excel automatically when there is a change in unique values and data below the formula?

asked 2023-07-17 09:53:11 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-17 10:20:02 +0000

huitzilopochtli gravatar image

Yes, a VBA code can be written to add or delete rows in Excel automatically when there is a change in unique values and data below the formula. The code can be tailored specifically to the requirements of the user. Here is an example code that adds a row when a unique value changes:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim LastRow As Long
    Dim CheckRange As Range
    Dim i As Long

    Set CheckRange = Range("A1:A" & Rows.Count)
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row

    'Check if the change was in column A
    If Not Intersect(Target, CheckRange) Is Nothing Then
        'Check for unique values in column A
        For i = LastRow To 2 Step -1
            If Cells(i, 1).Value <> Cells(i - 1, 1).Value Then
                'Insert a row at the change in value
                Rows(i).Insert Shift:=xlDown
            End If
        Next i
    End If

End Sub

To delete rows when the data changes, simply replace the Rows(i).Insert Shift:=xlDown with Rows(i).Delete Shift:=xlUp.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-17 09:53:11 +0000

Seen: 11 times

Last updated: Jul 17 '23