输入新行并从上面的单元格中复制公式

时间:2013-10-09 11:12:48

标签: excel vba

我正在尝试创建一个执行以下操作的Excel宏:

  1. 在文档末尾输入新行

  2. 从上面的单元格中复制公式

  3. 到目前为止,我有这个:

        Sub New_Delta()
    
        ' Go to last cell
        Range("A4").Select
        Selection.End(xlDown).Select
        LastCell = [A65536].End(xlUp).Offset(-1, 0).Address
        Range(LastCell).Select
    
        ' Enter new line
        Selection.EntireRow.Insert Shift:=xlUp, CopyOrigin:=xlFormatFromLeftOrAbove
    
        ' Copy formula from cell above
        Dim oCell As Range
            For Each oCell In Selection
                If (oCell.Value = "") Then
                oCell.Offset(-1, 0).Copy Destination:=oCell
                End If
            Next oCell
    
    End Sub
    

    这将复制第一个单元格“A”的公式,但不复制以下单元格的公式

    我想做Selection.Offset(0, 1).Select之类的事情然后再迭代到“K”(最好没有“G”和“H”)

    但是我被困住了,可以真正使用一些帮助。

    编辑:我想要这样的东西(非工作伪代码)

        ' Copy formula from cell above
    Dim oCell As Range
            While (oCell.Offset(-1, 0).Value != "") ' If the cell above is not empty
            oCell.Offset(-1, 0).Copy Destination:=oCell ' Copy the formula from the cell above
            Selection.Offset(0, 1).Select ' Move one cell to the right
    

1 个答案:

答案 0 :(得分:6)

您只需将行复制/插入新行

即可
Sub New_Delta()

  ' Go to last cell
  Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select

  ' Copy formula from cell above
  Rows(Selection.Row - 1).Copy
  Rows(Selection.Row).Insert Shift:=xlDown

End Sub