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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19270471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:50:38  来源:igfitidea点击:

Enter a new line and copy formula from cells above

excelvba

提问by Jon Carlstedt

I am trying to create an Excel macro that does the following:

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

  1. Enter a new line at the end of document

  2. copy the formulas from the cells above

  1. 在文档末尾输入一个新行

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

So far I have this:

到目前为止,我有这个:

    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

This copies the formula for the first cell "A" but not the following ones

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

I want to do something like Selection.Offset(0, 1).Selectand then iterate over that up to "K" (preferably without "G" and "H")

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

But I'm stuck, and could really use some help.

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

EDIT: I want something like this (Non working pseudo code)

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

    ' 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

回答by K_B

You could simply copy/insert the row before into the new row

您可以简单地将之前的行复制/插入到新行中

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