【发布时间】:2016-12-15 05:22:41
【问题描述】:
如何使用 VBA 将最后一个非空行值复制到另一个工作表?
【问题讨论】:
-
@Jeeva 你有没有试过你得到的任何答案?任何反馈 ?谢谢?
-
@Jeeva 真的吗?您一直更喜欢
Select的答案? -
老实说,我不在乎代码的设计方式,只要它能产生我想要的结果。
如何使用 VBA 将最后一个非空行值复制到另一个工作表?
【问题讨论】:
Select 的答案?
使用这个子来做到这一点。
Sub CopyPaste()
Range("A1").End(xlDown).Select
Rows(Selection.Row).Select
Selection.Copy
Sheets("Sheet2").Activate
Range("A1").Select
ActiveSheet.Paste
End Sub
【讨论】:
Select、Selection和Activate和ActiveSheet?
作为一种好习惯,远离Select、Selection、Activate等...
请改用Sheets 和Ranges 等引用对象。还要花时间学习如何使用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
【讨论】:
由于您对“值”感兴趣而不是无用地复制已使用范围之外的单元格,因此您可以执行以下操作:
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
【讨论】: