Excel VBA to run Macro in new row is Inserted

前端 未结 3 1076
迷失自我
迷失自我 2021-01-19 02:22

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 a

3条回答
  •  走了就别回头了
    2021-01-19 03:20

    There are two main issues in your code

    1. You are causing an Event Cascade. Ie your Change event is triggering further change events
    2. .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
    

提交回复
热议问题