Sub MyInsertRows()
Dim lr As Long
Dim r As Long
Dim ct As Long
Dim cur As Variant
Dim prv As Variant
Application.ScreenUpdating = False
' Find last row with data in column A
lr = Cells(Rows.Count, "A").End(xlUp).Row
' Loop through all rows backwards, up to row 2
For r = lr To 2 Step -1
' Get current value
cur = Cells(r, "A")
' Count number of records in column matching value in column A
ct = Application.WorksheetFunction.CountIf(Range("A:A"), cur)
' If count is less than three and a different value, then insert rows below
If (ct < 3) And (cur <> prv) Then
Rows(r + 1 & ":" & r + 3 - ct).Insert
End If
' Set previous value to current value
prv = cur
Next r
Application.ScreenUpdating = True
MsgBox "Macro complete!"
End Sub
Thank you so much Joe. It works perfectly with small group of data, e.g. ~500 rows but when I tried to include more it started to not work.Welcome to the Board!
Assuming that:
- Your data is in column A and begins on row 2 (row 1 is a header)
- Your data in column A is already sorted (if not, we can add code to do that)
Here is VBA code that should do what you want:
VBA Code:Sub MyInsertRows() Dim lr As Long Dim r As Long Dim ct As Long Dim cur As Variant Dim prv As Variant Application.ScreenUpdating = False ' Find last row with data in column A lr = Cells(Rows.Count, "A").End(xlUp).Row ' Loop through all rows backwards, up to row 2 For r = lr To 2 Step -1 ' Get current value cur = Cells(r, "A") ' Count number of records in column matching value in column A ct = Application.WorksheetFunction.CountIf(Range("A:A"), cur) ' If count is less than three and a different value, then insert rows below If (ct < 3) And (cur <> prv) Then Rows(r + 1 & ":" & r + 3 - ct).Insert End If ' Set previous value to current value prv = cur Next r Application.ScreenUpdating = True MsgBox "Macro complete!" End Sub
It should not have any problem with 500 rows. I don't there is anything in the code that would cause the number of rows to affect how it works.Thank you so much Joe. It works perfectly with small group of data, e.g. ~500 rows but when I tried to include more it started to not work.