0

我在将多个工作表中的数据合并到摘要工作表中时遇到问题。它能够复制所有数据,除非粘贴数据时它会覆盖以前的数据。表 A 中的示例数据被粘贴到从范围 A2 开始重新编译表。问题是工作表 B、C、D 等中的数据也将从 A2 范围开始粘贴,导致其相互覆盖。这是我的代码。

   Private Sub CommandButton2_Click()
   Dim Sheetname, myrange As String
   Dim A, noOfrows As Integer
   Dim startRow As Integer

   For i = 2 To Worksheets("Master Sheet").Cells.SpecialCells(xlCellTypeLastCell).Row

   Sheetname = Worksheets("Master Sheet").Cells(i, 27).Value'All the sheets that suppose to transfer to recompile sheet 
     noOfrows = Worksheets(Sheetname).Cells.SpecialCells(xlCellTypeLastCell).Row
     myrange = "A2:N" & CStr(noOfrows)
     Worksheets(Sheetname).Select
     Worksheets(Sheetname).Range(myrange).Select
     Selection.Copy
     Sheets("Recompile").Select         
     Range("A2").Select
     ActiveSheet.Paste

     Next i

     End Sub
4

1 回答 1

0

您需要在“重新编译”表中找到 UsedRange 并粘贴到以下范围:

就像是:

私有子 CopyData()

Dim A As Long
Dim noOfrows As Long
Dim startRow As Long
Dim i As Long

Dim control As Worksheet
Dim source As Worksheet
Dim target As Worksheet

Set control = Worksheets("Master Sheet")
Set target = Worksheets.Add

For i = 2 To control.UsedRange.Rows.Count
    ' the target worksheet for this row of data
    Set source = Worksheets(control.Cells(i, 1).Value) ' My example has this data in column A

    ' the address of a range with (number of rows - 1) for columns A:N
    source.Range("A2:N" & source.UsedRange.Rows.Count).Copy
    target.Range("A" & target.Cells.SpecialCells(xlCellTypeLastCell).Offset(1, 0).Row).PasteSpecial xlPasteValues
Next i

End Sub

这里有很多信息和提示:http ://www.rondebruin.nl/win/s3/win002.htm

于 2013-11-13T09:40:25.183 回答