Insert row everytime a cell value changes

midoop

New Member
Joined
Aug 9, 2013
Messages
37
Good morning,I am trying to write a VBA script that inserts a row every time a cell value changes. The number of rows that contain cell value A, for example, is a dynamic number (e.g. there's no set number of rows). Below is my code:
Code:
myrows = WorksheetFunction.CountA(ws1.Range("A:A"))For i = 2 To myrows    If Cells(i, 2) <> Cells(i + 1, 2) Then    Cells(i, 2).Select    ActiveCell.Offset(1).EntireRow.Insert    End If    Next i
This code inserts rows, but it inserts several hundreds of rows all together, and not everytime the cell value of interest changes.Any and all help is greatly appreciated!
 

Excel Facts

Copy formula down without changing references
If you have =SUM(F2:F49) in F50; type Alt+' in F51 to copy =SUM(F2:F49) to F51, leaving the formula in edit mode. Change SUM to COUNT.
Give this guy a go, and please be sure to back up your excel workbook before running this macro!


Code:
Sub InsertRows()
  Dim lngLstRow As Long

  lngLstRow = Range("A" & Rows.Count).End(xlUp).Row
  For i = lngLstRow To 2 Step -1
    If Not IsEmpty(Range("A" & i)) Then
      If Range("A" & i) <> Range("A" & i - 1) Then
        Range("A" & i).EntireRow.Insert
      End If
    End If
  Next
End Sub
 
Upvote 0
Thank you for responding! I got the following to work:
Code:
myrows = WorksheetFunction.CountA(ws1.Range("A:A"))
For i = 2 To myrows
    If Cells(i, 2) <> Cells(i - 1, 2) Then
    Rows(i).Insert xlShiftDown
    i = i + 1
    End If
    
Next i
Rows(2).Delete Shift:=xlUp

Thank you though! :-)
 
Upvote 0

Forum statistics

Threads
1,223,164
Messages
6,170,444
Members
452,326
Latest member
johnshaji

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top