【问题标题】:copy last row with data to next row down将带有数据的最后一行复制到下一行
【发布时间】:2014-07-08 23:22:34
【问题描述】:

我想将包含公式的最后一行从工作表复制到下一行,然后对我刚刚复制的行进行赋值。例如,我在 A 到 W 列中有公式,我当前的最后一行是 10,我想将第 10 行复制到第 11 行,然后计算第 10 行的值。试图让 vba 代码自动处理。任何帮助表示赞赏。

【问题讨论】:

  • 能否请您先发布您自己的代码,并告诉我们它在哪里引发了错误?
  • 你试过什么?询问不包含任何现有尝试的代码的问题往往会在这里很快关闭。

标签: vba copy


【解决方案1】:

这应该会让你朝着正确的方向开始:

Sub appendToEnd()

    Dim myLastCell As Range
    Set myLastCell = LastCell(Worksheets("Sheet1").Range("A:W"))
    Dim lastCellCoords As String: lastCellCoords = "A" & myLastCell.Row & ":W" & myLastCell.Row

    Dim firstEmptyRow As Integer: firstEmptyRow = myLastCell.Row + 1
    Dim firstEmptyCoords As String: firstEmptyCoords = "A" & firstEmptyRow & ":W" & firstEmptyRow

    If Not myLastCell Is Nothing Then
        ' Now Copy the range:
        Worksheets("Sheet1").Range(lastCellCoords).Copy
        ' And paste to first empty row
        Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
        Application.CutCopyMode = False
    Else
        MsgBox ("There is no data in specified range")
    End If

End Sub

Function LastCell(r As Range) As Range

'
' Note "&" denotes a long value; "%" denotes an integer value

    Dim LastRow&, lastCol%

    On Error Resume Next

    With r

  ' Find the last real row

    LastRow& = .Cells.Find(What:="*", _
      SearchDirection:=xlPrevious, _
      SearchOrder:=xlByRows).Row

  ' Find the last real column

    lastCol% = .Cells.Find(What:="*", _
      SearchDirection:=xlPrevious, _
      SearchOrder:=xlByColumns).Column

    End With

' Finally, initialize a Range object variable for
' the last populated row.

    Set LastCell = r.Cells(LastRow&, lastCol%)


End Function

【讨论】:

  • 这很好用。我不得不稍微调整一下,因为它将值粘贴到最后一行并将公式保留在前最后一行,但您的回答非常有帮助。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多