从多张纸复印并粘贴到纸张1中

时间:2015-09-29 21:40:29

标签: vba loops copy copy-paste worksheet

我正在尝试从多个工作表中获取数据并粘贴到工作表1中,但我的代码无法正常工作。它不断地从表格“表1”中复制。有谁知道我的代码出了什么问题?

由于

Option Explicit

Sub test()

Dim ws As Worksheet
Dim i As Integer

    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "Table 1" Then

            ActiveSheet.Range("A15:X35").Select
            Selection.Copy

            Worksheets("Table 1").Activate

                For i = 1 To 5000

                    If IsEmpty(Cells(i, 1)) = True And IsEmpty(Cells(i + 1, 1)) = True Then
                    ActiveSheet.Cells(i, 1).Select
                    ActiveSheet.Paste
                    Exit For
                    End If

                Next i

        End If
    Next ws

End Sub

1 个答案:

答案 0 :(得分:0)

在你的循环中,你是从ActiveSheet复制而不是从ws复制。如果activeSheet是&#34;表1&#34; (事实上​​,你自己在Worksheets("Table 1").Activate语句中激活了表1,然后当然会继续复制它。

此外,不使用激活和选择直接从范围复制总是更好。我想这就是你想要做的事情:

With Worksheets("Table 1")
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "Table 1" Then
            For i = 1 To 5000
                If IsEmpty(.Cells(i, 1)) And IsEmpty(.Cells(i + 1, 1)) Then
                    ws.Range("A15:X35").Copy .Cells(i, 1)
                    Exit For
                End If
            Next i
        End If
    Next ws
End With