循环复制另一个工作簿中的工作表

时间:2019-03-21 07:34:03

标签: excel

For Each ws In punchcalc.Worksheets
    ws.Range("D11:L33").Copy
    reportfile.Activate
    reportfile.Sheets(Index).Range("D11").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
    SkipBlanks:=False, Transpose:=False
    Index = Index + 1
    Next ws
End Sub

此代码仅在工作一秒钟的循环中出现错误

2 个答案:

答案 0 :(得分:1)

从不使用选择

    For Each ws In punchcalc.Worksheets
      ws.Range("D11:L33").Copy
      reportfile.Sheets(Index).Range("D11").PasteSpecial Paste:=xlPasteValues
      Index = Index + 1
    Next ws

答案 1 :(得分:0)

以下代码提供了一些有关如何执行操作的准则。因此,修改代码并尝试:

Option Explicit

Sub test()

    Dim wbSource As Workbook, wbDestination As Workbook
    Dim ws As Worksheet
    Dim Lastrow As Long

    'Let us assume that you run the code from another workbook (NOT wbSource or wbDestination) & both workbooks are closed. At the end of the code you can close the workbooks if you want to.
    Set wbSource = Workbooks.Open("C:\xx\xx\xx\xx\Source") 'Open wbSource
    Set wbDestination = Workbooks.Open("C:\x\xx\xx\xx\Destination") 'Open wbDestination

    For Each ws In wbSource.Worksheets 'Loop wbSource Sheet1

        With wbDestination.Worksheets("Sheet1")
            Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row 'Find wbDestination, Sheet1 Last row
        End With

        ws.Range("A1").Copy wbDestination.Worksheets("Sheet1").Range("A" & Lastrow + 1) 'Paste wbSource.ws.Range("A1").value to wbDestination.Sheet1.Range("A" & Lastrow + 1)

    Next ws

End Sub