我尝试从一个工作簿中复制AJ到AQ列中的数据,然后将这些值粘贴到新工作簿中。行数是可变的(取决于用户)。我尝试过实现以下代码,但它只将第一行粘贴到新工作簿中:
Dim i, j, LastRow, LastRow2
Set OldBook = ActiveWorkbook
Set NewBook = Workbooks.Add(xlWBATWorksheet)
With NewBook
.ActiveSheet.Name = "GMD"
End With
OldBook.Activate
Sheets("Entry Sheet").Select
LastRow = ActiveSheet.Range("AJ" & Rows.Count).End(xlUp).Row ''Finds the last row of the column with text
LastRow2 = ActiveSheet.Range("AQ" & Rows.Count).End(xlUp).Row ''Finds the last row of the column with text
For i = 1 To LastRow ''Sets the range of rows to be copied including header
Range(Cells(i, 36), Cells(i, 43)).Select ''Selects relevant columns
Selection.Copy
NewBook.Activate
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues
OldBook.Activate
Sheets("Entry Sheet").Select
Next i
For j = 1 To LastRow ''Sets the range of Rows to be copied including header
Range(Cells(j, 43), Cells(j, 44)).Select ''Selects relevant columns
Selection.Copy
NewBook.Activate
Range("H1").Select
ActiveSheet.Paste
OldBook.Activate
Sheets("Entry Sheet").Select
Next j
对我做错了什么的任何观察?
答案 0 :(得分:2)
问题是,在粘贴部分中,您只调用第一个单元格并且它处于循环中,因此每次循环将粘贴到单元格A1中。
此外,如果你想要的只是值,最好跳过剪贴板并直接分配值。有了它,你可以避免循环。
第三,避免使用选择。
编辑:删除循环并添加换行符的换行文本。
Dim i, LastRow
Dim ws As Worksheet
Set oldbook = ActiveWorkbook
Set ws = oldbook.Sheets("Entry Sheet")
Set newbook = Workbooks.Add(xlWBATWorksheet)
With newbook
.ActiveSheet.Name = "GMD"
End With
With ws
LastRow = .Range("AJ" & .Rows.Count).End(xlUp).Row ''Finds the last row of the column with text
newbook.Sheets("GMD").Range(newbook.Sheets("GMD").Cells(1, 1), newbook.Sheets("GMD").Cells(LastRow, 7)).Value = .Range(.Cells(1, 36), .Cells(LastRow, 43)).Value
End With
newbook.Sheets("GMD").Range("H:I").WrapText = True