将许多Excel工作簿和工作表中的数据导入到单个工作簿/表中

时间:2011-01-05 23:58:51

标签: excel vba loops import

我有54个excel文件,每个文件有三个,每个工作表有不同数量的数据条目,但是它们以相同的格式设置,我需要使用VBA将这些工作表中的数据导入到单个工作簿中。

有什么方法可以编程,所以我可以构建循环来导入数据,但不必为每个循环/工作表写入每个工作簿名称?我想我可以使用call函数,但我不知道如何使循环代码独立于它们适用的工作簿名称。

提前非常感谢,

米莉

2 个答案:

答案 0 :(得分:3)

当然只需将文件夹中的工作簿循环打开它们然后在它们的工作表上循环。根据格式的细微差别,您可能需要在导入时执行一些额外的工作。

Sub ImportWorkbooks(destination as workbook, importFolderPath As String)

    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    'Get the folder object associated with the directory
    Set objFolder = objFSO.GetFolder(importFolderPath)

    'Loop through the Files collection and import each workbook
    For Each objFile In objFolder.Files
        Dim source As Workbook
        Set source = Application.Workbooks.Open(objFile.Path, ReadOnly:=True)
        ImportWorkbook source, destination
        wb.Close
        Set wb = Nothing
    Next

    Set objFolder = Nothing
    Set objFile = Nothing
    Set objFSO = Nothing

End Sub

Sub ImportWorkbook(source As Workbook, destination as Workbook)
    Dim sheet As Worksheet

    'Import each worksheet
    For Each sheet In source.Sheets
        ImportWorksheet sheet, destination
    Next sheet
End Sub

Sub ImportWorksheet(sheet As Worksheet, destination as Workbook)

    'Perform your import logic for each sheet here (i.e. Copy from sheet and paste into a 
    'sheet into the provided workbook)

End Sub

基本用法类似于以下内容导入当前工作簿:

ImportWorkbooks ThisWorkbook, "c:\path\to\folder\containing\workbooks\to\import"

答案 1 :(得分:1)

它只需要两件事: 包含工作簿文件名的数组,例如

 dim books
 books = array("book1.xls","book2.xls",....)

然后你的循环代码看起来像

dim myBk as Workbook
dim bkFile as string
For Each bkFile in books
   myBk = Workbooks.Open(bkFile, ReadOnly)
   myBk.Activate
   'Transfer cells from myBk to target workbook
   target.cells(--).Value = myBk.Sheets("myStuff").Cells(--) 
   ...
Next

我无法帮助你了解细节。您需要为循环中的每次传递更改target.cells参数以移动数据目标。