如何使用VBA将来自不同Excel选项卡的数据组合到主表中

时间:2016-03-08 22:23:54

标签: excel vba excel-vba

我使用以下脚本将多表Excel文件的“Sheet1”中的数据复制到另一个Excel文件的主表中。它适用于一张纸。现在我需要让它运行所有将数据粘贴到主文件中下一个可用行的工作表。

请注意:所有工作表都使用相同的密码。

请帮忙!

谢谢,

Yohanan

Sub CopyRanges()
Dim WB1 As Workbook
Dim WB2 As Workbook
Dim LastRow As Long

Set WB1 = ActiveWorkbook
Set WB2 = Workbooks.Open(WB1.Path & "\Datafile.xls")

Sheets("Sheet1").Unprotect ("Password1")

With WB2.Sheets("Sheet1")
  LastRow = .Range("B" & .Rows.Count).End(xlUp).Row
End With
WB2.Sheets("71235").Range("B6:M" & LastRow).Copy
WB1.Sheets("Output").Range("A2").PasteSpecial xlPasteValues

Sheets("Sheet1").Protect ("FTCCTOR")
WB2.Close
End Sub

1 个答案:

答案 0 :(得分:2)

试试这个:

Sub CopyRanges()
Dim WB1 As Workbook
Dim WB2 As Workbook
Dim LastRow As Long
Dim sht As Worksheet

Set WB1 = ActiveWorkbook
Set WB2 = Workbooks.Open(WB1.Path & "\Datafile.xls")

For Each sht In WB2.Sheets
    With sht
        .Unprotect ("Password1")
        LastRow = .Range("B" & .Rows.count).End(xlUp).Row
        WB1.Sheets("Output").Range("A" & WB1.Sheets("Output").Rows.count).End(xlUp).Resize(LastRow - 5, 12).value = .Range("B6:M" & LastRow).value
        .Protect ("Password1")
    End With
Next sht
WB2.Close
End Sub

当只想要值时,分配值比复制它们更快。