Excel VBA to run Macro in new row is Inserted

前端 未结 3 1071
迷失自我
迷失自我 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:22

    Like @laughsloudly said, what your code is doing now is once you make a change anywhere in the range A1:D25 it will start inserting rows until Excel runs out of rows, it's an open loop.

    The code:

    If Target.Range("A1:D25") = ActiveCell.EntireRow.Insert Then
    

    Is meant to check whether the action taken is within the range you want to be monitored. You don't want to be performing an action in this line. Rather, you want something more like:

    If Target.Range("A1:D25") = ActiveCell Then
    

    This will allow you to run code based on actions in your sheet. However, your statement "I am trying to have my spreadsheet automatically take the previous rows format and formulas when a new row is inserted." isn't entirely logical. I presume that you mean to copy all formats from the above row and only formulas from certain cells, correct? So, let's say if you have rows that all have formulas relative to column A, you don't want to copy all of the row, because you will overwrite A. Furthermore, in this case, you only want to monitor column A.

    So let's say you have formulas in columns B through K that rely on column A, then you only want changes to column A to affect the spreadsheet. Then your code would look something like this:

    Private Sub Worksheet_Change(ByVal Target As Range)
    
        If Target.Column = ActiveCell.Column Then
            refRow = Target.Row - 1
            thisRow = Target.Row
            Range("B" & refRow & ":K" & refRow).Copy Range("B" & thisRow & ":K" & thisRow)
        End If
    
    End Sub
    

    This copies down everything but column A when you make a change to A. And, as alluded to previously, you don't want the code making any changes to column A (in this case) without something to break it out of that recursive loop. Best just to apply conditional formatting to any column that you are assigning as the target.

    Hope that helps,

    n8

提交回复
热议问题