NewbieFromNJ
New Member
- Joined
- May 12, 2021
- Messages
- 3
- Office Version
- 365
- Platform
- Windows
- MacOS
- Mobile
- Web
Welcome to the Board!
In order for VBA code to run automatically, there has to be some "event" that triggers it to run, like the opening of a file, the selection of a particular cell, or the update of a particular cell.
What would be the "event" to automatically trigger the VBA to run in this case?
The other option is to run the VBA code on command.
Sub MyInsertRows()
Dim lr As Long
Dim r As Long
Application.ScreenUpdating = False
' Find last row in column B with data
lr = Cells(Rows.Count, "B").End(xlUp).Row
' Loop through rows backwards
For r = lr To 3 Step -1
' Compare value in column B with value in row above it
If Cells(r, "B") <> Cells(r - 1, "B") Then
Rows(r & ":" & r + 1).EntireRow.Insert
End If
Next r
Application.ScreenUpdating = True
End Sub
Try this code.
You can assign it to a command button, or keyboard shortcut, if you like:
VBA Code:Sub MyInsertRows() Dim lr As Long Dim r As Long Application.ScreenUpdating = False ' Find last row in column B with data lr = Cells(Rows.Count, "B").End(xlUp).Row ' Loop through rows backwards For r = lr To 3 Step -1 ' Compare value in column B with value in row above it If Cells(r, "B") <> Cells(r - 1, "B") Then Rows(r & ":" & r + 1).EntireRow.Insert End If Next r Application.ScreenUpdating = True End Sub
where and/or what would I change it if I needed to amend the number of blank rows to add. Let's say, if I'd rather have 1 row inserted instead of two?
Rows(r & ":" & r + 1).EntireRow.Insert
Rows(r).EntireRow.Insert