复制一系列单元格并仅将同一范围内的值粘贴到另一个 sheet

Copying a range of cells and paste only values in the same range in another sheet

我有这个循环,遍历 sheet 行,我需要将相同范围的单元格粘贴到具有相同结构的另一个 sheet 中。

 For i = 1 To NumRows 
            
                
                Set rng = sheet.Range("D" & i)
                rng.EntireRow.Copy otherSheet.Cells(i + LastRow, 1)
                
                
                
 Next i 

现在,如果我只需要将 Entirerow 中的值粘贴到 'otherSheet',我该如何实现?

请测试下一个代码。它假定您在每个 sheet 中的第一行可以像参考一样使用来计算要计算的列数。如果不是这种情况,请指定要使用的行:

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

如果您想避免复制 headers,您应该将 sh.Range("A1"... 替换为 sh.Range("A2"...。这意味着数组是从第二行开始构建的。