如何使用VBA将最后一个非空行值复制到另一个工作表?

时间:2016-12-15 05:22:41

标签: excel vba macros

如何使用VBA将最后一个非空行值复制到另一个工作表?

3 个答案:

答案 0 :(得分:0)

使用此子语言。

    Sub CopyPaste()
        Range("A1").End(xlDown).Select
          Rows(Selection.Row).Select
           Selection.Copy
           Sheets("Sheet2").Activate
          Range("A1").Select
        ActiveSheet.Paste
    End Sub

答案 1 :(得分:0)

作为良好做法,请远离SelectSelectionActivate等...

而是使用SheetsRange等引用的对象。还花时间学习如何使用With语句,它将帮助您创建更短更清晰的代码,并减少错误的机会。

Option Explicit

Sub CopyPaste()

Dim LastRow As Long

' copy last row from "Sheet1" >> modify to your sheet's name
With Sheets("Sheet1")
    ' find last row with data in column A , skip empty cells in the middle
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    ' copy entire row with data from "Sheet1" to "Sheet2" first cell ("A1")
    .Rows(LastRow).Copy Destination:=Sheets("Sheet2").Range("A1")

End With

End Sub

答案 2 :(得分:0)

因为您对"值"感兴趣并且不要无用地复制使用范围之外的单元格,你可以这样做:

Sub CopyPaste()
    With Sheets("SourceSheetName") '<--| reference "source" sheet (change "SourceSheetName" to your actual "source" sheet name)
        ' find last row with data in column A , skip empty cells in the middle
        With Range(.Cells(.Rows.count, "A").End(xlUp), _
                   .Cells(.Cells(.Rows.count, "A").End(xlUp).row, .Columns.count).End(xlToLeft)) '<--| reference its range from its column A last not empty cell to this latter cell row last not empty cell
            Worksheets("TargetSheetName").Range("A1").Resize(, .Columns.count).Value = .Value '<--| paste values to "target" sheet starting from its cell A1 (change "TargetSheetName" to your actual "target" sheet name)
        End With
    End With
End Sub