VBA代码循环并编译来自多个工作簿的特定工作表

时间:2017-06-27 04:46:01

标签: excel vba excel-vba

我有一个包含约20个工作簿的文件夹,这些工作簿都有不同的文件名,我需要将每个工作簿中的特定工作表拉到一个主工作簿中。我对VBA并不熟悉,但我希望有人可以将我的伪代码转换成适用于Excel的VBA脚本。

create wrkbk_names as array
store workbook names in "folder" to wrkbk_names
for each book in wrkbk_names
    for each worksheet in book
         if worksheet.name = "targetSheet"
              copy worksheet("targetSheet") to Mainbook.xlxs 

工作簿非常大,有50张以上的书/书,所以如果我可以在没有激活的情况下打开它们,这将大大加快这个过程。我试图提取的特定工作表在所有工作簿中具有相同的名称,尽管我对索引不太确定。

如果脚本可以将单元格从工作表复制到Mainbook的下一个空行,那么将获得奖励积分,以便将来自20个工作簿的所有targetSheet数据编译为Mainbook的1个工作表。

1 个答案:

答案 0 :(得分:0)

如果您特别喜欢使用VBA执行此操作,请考虑使用Scripting.FileSystemObject(通过工具 - >引用添加对 Microsoft Scripting Runtime 的引用... ):

'Assuming you are running this within Excel
'otherwise you'll have to create an Excel instance

'This also assumes that the target workbook is the currently active workbook
'in the Excel instance

Dim mainBook As Workbook
Set mainBook = ActiveWorkbook

Dim fso As New Scripting.FileSystemObject
Dim fle As Scripting.File
Dim book As Workbook
For Each fle In fso.GetFolder("C:\folder").Files

    'Should probably check here that the file is actually an Excel file

    Set book = Workbooks.Open(fle.Path)
    Dim wks As Worksheet
    For Each wks In book.Worksheets
        If wks.Name = "targetSheet" Then
            wks.Copy mainBook.Worksheets(1) 'copies to the start of the main workbook
        End If
    Next
    book.Close
Next