我目前正在使用以下代码来复制粘贴范围,但是一旦粘贴了数据就会创建一个非常大的文件,如何将其修改为仅粘贴到最后一个活动行?或者由于某些其他因素,文件变大了? VB的新手,非常感谢任何帮助。
Private Sub CommandButton1_Click()
Dim WB1 As Workbook
Dim WB2 As Workbook
Set WB1 = ActiveWorkbook
Set WB2 = Workbooks.Open(WB1.Path & "\RawData.xlsm")
WB1.Sheets("CR Details").Columns("A:AW").Value = WB2.Sheets("sheet1").Columns("A:AW").Value
WB2.Close
End Sub
答案 0 :(得分:3)
文件大小是使用整个列的结果。这个link涵盖了一些查找数据范围结束的方法。在您的子目录中,您可以这样做:
Private Sub CommandButton1_Click()
Dim WB1 As Workbook
Dim WB2 As Workbook
Set WB1 = ActiveWorkbook
Set WB2 = Workbooks.Open(WB1.Path & "\RawData.xlsm")
'Find the last row with data
With WB1.Sheets("CR Details")
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
End With
WB1.Sheets("CR Details").Range("A1:AW" & LastRow).Copy
WB2.Sheets("sheet1").Range("A1").PasteSpecial xlPasteValues
WB2.Close
End Sub
答案 1 :(得分:0)
您问题的简短回答是:
Private Sub CommandButton1_Click()
Dim WB1 As Workbook
Dim WB2 As Workbook
Dim LastRow As Long
Set WB1 = ActiveWorkbook
Set WB2 = Workbooks.Open(WB1.Path & "\RawData.xlsm")
With WB1.Sheets("CR Details")
'Find the last cell's row with data in any column
'(You can also use ".Cells(Rows.Count, 1).End(xlUp).row")
LastRow = .Range("A:AW").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
'Copy the values
WB2.Sheets("sheet1").Range("A1", "AW" & LastRow) = .Range("A1", "AW" & LastRow).Value
End With
WB2.Close
End Sub
更详细的解释:
要查找最后使用的行的一个非常常见的代码段是:
(将使用A列查找最后使用的行)
Dim LastRow as Long
With ThisWorkbook.Sheets("CR Details")
LastRow = .Cells(Rows.Count, 1).End(xlUp).row
End With
将“1”更改为您要查看的列号。
要查找range("A:AW")
中任何列中最后一个使用过的单元格的行,那么您需要这样的内容:
Dim LastRow as Long
With ThisWorkbook.Sheets("CR Details").Range("A:AW")
LastRow = .Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
End With
就是这样。 Ron de Buin有一个很好的页面解释了这一点。答案也可以在Stack Overflow上找到。