Copying formula to the next row when inserting a new row

前端 未结 5 633
轮回少年
轮回少年 2021-02-12 15:05

I have a row in which there are formulas using values of the same row. The next row is empty, just with a different background color.

Now, if I insert a new row (by righ

5条回答
  •  青春惊慌失措
    2021-02-12 16:05

    Private Sub Worksheet_Change(ByVal Target As Range)

    'data starts on row 3 which has the formulas
    'the sheet is protected - input cells not locked - formula cells locked
    'this routine is triggered on change of any cell on the worksheet so first check if
    ' it's a cell that we're interested in - and the row doesn't already have formulas
    If Target.Column = 3 And Target.Row > 3 _
    And Range("M" & Target.Row).Formula = "" Then
    
        On Error GoTo ERROR_OCCURRED
    
        'unprotect the sheet - otherwise can't copy and paste
        ActiveSheet.Unprotect
        'disable events - this prevents this routine from triggering again when
        'copy and paste below changes the cell values
        Application.EnableEvents = False
    
        'copy col D (with validation list) from row above to new row (not locked)
        Range("D" & Target.Row - 1).Copy
        Range("D" & Target.Row).PasteSpecial
    
        'copy col M to P (with formulas) from row above to new row
        Range("M" & Target.Row - 1 & ":P" & Target.Row - 1).Copy
        Range("M" & Target.Row).PasteSpecial
    

    'make sure if an error occurs (or not) events are re-enabled and sheet re-protected

    ERROR_OCCURRED:

        If Err.Number <> 0 Then
            MsgBox "An error occurred. Formulas may not have been copied." & vbCrLf & vbCrLf & _
                Err.Number & " - " & Err.Description
        End If
    
        're-enable events
        Application.EnableEvents = True
        're-protect the sheet
        ActiveSheet.Protect
    
        'put focus back on the next cell after routine was triggered
        Range("D" & Target.Row).Select
    
    End If
    

    End Sub

提交回复
热议问题