I am trying to have my spreadsheet automatically take the previous rows format and formulas when a new row is inserted.
I read where you can set up your sheet to automatically run the code if a change is made, but I am having a hard time getting the code to work.
I have tried the following and every time I insert a new row it keeps adding a row until it gets an error and I have to force quit:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Range("A1:D25") = ActiveCell.EntireRow.Insert Then
Cells(1, 2).Value = 10
End If
End Sub
I added the Cell Value = 10
to see if it would work. It was just a test, but it still fails.
Does anyone know a possible solution?
Run Macro When a Cell Changes (Method 1)Go to the VBA Editor (Alt + F11) and double-click the name of the spreadsheet that contains the cell that will change or just right-click the worksheet tab and click View Code.
Hit the Set Next Statement option in the menu. That's equivalent to dragging the arrow to that line. (Ctrl-F9 is the hotkey for this action.) If you want it to quickly execute every line up to a certain line, set a breakpoint then hit run instead of stepping through the code line by line.
There are two main issues in your code
.Insert
doesn't do what you seem to think it does. It doesn't detect inserted rows, it Inserts rows.I am assuming by "... insert a new row ..." you mean Insert a whole row
This demo avoids the cascade with .EnableEvents = False
and uses Copy
, pasteSpecial
to copy formats and formulas.
Option Explicit
Dim RowsCount As Long ' Variable to track number of rows used in sheet
Private Sub Worksheet_Activate()
RowsCount = Me.UsedRange.Rows.Count
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo EH
' Detect whole row changed
If Target.Columns.Count = Me.Columns.Count Then
' Detect Extra Row
If RowsCount = Me.UsedRange.Rows.Count - 1 Then
' Copy Formulas and Format new row
Application.EnableEvents = False
If Target.Row > 1 Then
Target.Offset(-1, 0).Copy
Target.PasteSpecial xlPasteFormulas, xlPasteSpecialOperationNone, False, False
Target.PasteSpecial xlPasteFormats, xlPasteSpecialOperationNone, False, False
Application.CutCopyMode = False
End If
End If
RowsCount = Me.UsedRange.Rows.Count
End If
EH:
Application.EnableEvents = True
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With