Excel宏FOR EACH循环可将相同的范围粘贴到不同的工作表中并粘贴到下一列

时间:2019-04-30 13:53:59

标签: excel vba

我在工作簿中有几个工作表(工作表A,工作表B,工作表C)。我想从每个工作表中复制相同的范围,并将它们粘贴到另一个工作簿的工作表中,每个工作表都放在下一列中。我知道如何编写要复制的代码,但更难的部分是粘贴。这就是我的想法:

sub copypaste ()

dim wb as workbook 'this workbook
dim destination as workbook 'destination workbook
dim ws as worksheet
dim ws1 as worksheet '(in this workbook)
dim ws2 as worksheet '(in this workbook)
dim ws3 as worksheet '(in this workbook)
dim DestWorksheet as worksheet 

For Each ws in wb.worksheets  (referring to ws1, ws2, and ws3)
Range.("D1:D231").Copy

DestWorksheet.(I WANT TO PASTE DATA FROM WS1 in Column A in the destination worksheet, Ws2 in Column B, Ws3 in Column3) etc.

2 个答案:

答案 0 :(得分:0)

不使用复制和粘贴,效率低下

只需将一个范围的值放在您想要的位置的另一个范围内

DestWorksheet.Range("A1:A231").Value2 = Range("D1:D231").Value2
ws2.Range("B1:B231").Value2 = Range("D1:D231").Value2
ws3.Range("C1:C231").value2 = Range("D1:D231").Value2

答案 1 :(得分:0)

尝试以下方法。该代码同时使用工作表和列的索引,因此在第n个工作表中,迭代值也将粘贴到第n列。

请记住,我已放弃.Copy。如果仅 复制值并且使用我的代码更快,则不需要此功能。如果您不仅需要复制值,还可以将.Range(.Cells(1, i), .Cells(231, ...行替换为复制粘贴行。

Sub copypasta()

Dim i As Integer
Dim wb As Workbook
Set wb = ThisWorkbook
Dim ws As Worksheet

For i = 1 To wb.Sheets.Count
    With Workbooks(DESTINATION).Sheets(DESTINATION)
        .Range(.Cells(1, i), .Cells(231, i)).Value = wb.Sheets(i).Range("D1:D231").Value
    End With
Next i
End Sub