我有一个循环,在一个工作表行中循环,我需要在另一个具有相同结构的工作表中粘贴相同范围的单元格。
For i = 1 To NumRows
Set rng = sheet.Range("D" & i)
rng.EntireRow.Copy otherSheet.Cells(i + LastRow, 1)
Next i
现在,如果我只能将Entirerow中的值粘贴到"otherSheet"中,我该如何实现这一点?
请测试下一个代码。它假设每张工作表中的第一行可以像引用一样用于计算要计算的列数。如果不是这样,请指定要使用的行:
Sub testCopyRangeFromAllSheetsToMaster()
Dim sh As Worksheet, shCons As Worksheet, lastR As Long, lastC As Long
Dim lastRCons As Long, arr
Set shCons = Worksheets("otherSheet") 'use here your consolidation sheet to copy the range
For Each sh In ThisWorkbook.Sheets
If sh.Name <> shCons.Name Then
lastR = sh.Range("A" & rows.count).End(xlUp).row 'last row in the sheet to copy from
lastC = sh.cells(1, Columns.count).End(xlToLeft).Column 'last column
arr = sh.Range("A1", sh.cells(lastR, lastC)).Value 'Put the range in an array
lastRCons = shCons.Range("A" & rows.count).End(xlUp).row + 1 'last empty row in the consolidation sheet
'drop the array content at once:
shCons.Range("A" & lastRCons).Resize(UBound(arr), UBound(arr, 2)).Value = arr
End If
Next sh
MsgBox "Ready..."
End Sub
如果希望避免复制标头,则应将sh.Range("A1"...
替换为sh.Range("A2"...
。这意味着数组是从第二行开始构建的。