excel 如何复制并粘贴最后一行直到某个日期?

gkn4icbw  于 2023-06-30  发布在  其他
关注(0)|答案(1)|浏览(293)

我对VBA比较陌生。我在大学里上过一门课,自从使用它以来已经有好几年了。我试图多次复制电子表格中A列到S列的最后一行。我需要从A列最后一个单元格中指定的日期开始执行此操作,直到我在单元格A1中指定的日期。这将是一个报告,我每周更新,这就是为什么我试图这样做。我需要复制最后一行的所有公式。

Public Sub CopyLastRow()
    
    ' Define the source sheet (no need to activate it)
    Dim sourceSheet As Worksheet
    Set sourceSheet = ThisWorkbook.Worksheets("Steam Data")
    
    ' Find the last row in an specific column
    Dim lastRow As Long
    lastRow = sourceSheet.Range("A" & sourceSheet.Rows.Count).End(xlUp).Row
    
    ' Set the source range according to columns and last row
    Dim sourceRange As Range
    Set sourceRange = sourceSheet.Range("A" & lastRow & ":S" & lastRow)
   
   Dim x As Integer
   Dim lcell As Long
   
   lcell = Cells(Rows.Count, 1).End(xlUp).Row

   For x = lcell To x = Range("A1")
   
   If x < Range("A1") Then
    sourceRange.Copy
    sourceRange.Offset(1).PasteSpecial
    Else
    
    End If
   
  Next x
End Sub

我得到了这个工作作为一个简单的复制和粘贴。但是一旦我做了if语句,它就什么都不做,没有错误。知道我哪里做错了吗

xwbd5t1u

xwbd5t1u1#

代码的最后一部分需要进行调整,删除For ... Next循环(一开始就构造不当)并删除If ... Else ... End If。请看下面的代码片段:

Dim x As Integer
   Dim lcell As Long
   
   lcell = Cells(Rows.Count, 1).End(xlUp).Row

'   For x = lcell To 14   'x = Range("A1")
   
'   If x < Range("A1") Then
    sourceRange.Copy
    sourceRange.Offset(1).PasteSpecial
'    Else
    
'    End If
   
'  Next x

相关问题