【发布时间】:2011-06-04 08:59:08
【问题描述】:
我有 54 个 excel 文件,每个文件包含三张工作表,每张工作表都有不同数量的数据条目,但它们以相同的格式设置,我需要使用 VBA 将这些工作表中的数据导入到单个工作簿中。
有什么方法可以对其进行编程,以便我可以构建循环来导入数据,但不必为每个循环/工作表写入每个工作簿名称?我想我可以使用调用函数,但我不知道如何使循环代码独立于它们所应用的工作簿名称。
非常感谢您,
米莉
【问题讨论】:
我有 54 个 excel 文件,每个文件包含三张工作表,每张工作表都有不同数量的数据条目,但它们以相同的格式设置,我需要使用 VBA 将这些工作表中的数据导入到单个工作簿中。
有什么方法可以对其进行编程,以便我可以构建循环来导入数据,但不必为每个循环/工作表写入每个工作簿名称?我想我可以使用调用函数,但我不知道如何使循环代码独立于它们所应用的工作簿名称。
非常感谢您,
米莉
【问题讨论】:
只需要两件事: 包含工作簿文件名的数组,例如
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 参数以移动数据目标。
【讨论】:
当然,只需遍历文件夹中的工作簿,打开它们,然后遍历它们的工作表。根据格式的细微差别,您在导入时可能需要做一些额外的工作。
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"
【讨论】: