VBA可以实现一个文件夹内所有表格合并在一个数组里嘛?
时间: 2024-09-19 09:08:12 浏览: 39
是的,VBA(Visual Basic for Applications)可以实现这个功能。你可以编写一段代码来遍历指定文件夹内的所有Excel工作簿或表格,并将它们的内容添加到一个数组或者数据结构中。以下是一个简单的步骤概述:
1. 使用`Folder.Files`属性获取文件夹中的所有文件路径。
2. 遍历每个文件,判断是否为Excel (.xls, .xlsx) 文件。
3. 对于每个Excel文件,使用`Application.Workbooks.Open`打开它,然后读取工作表的数据。
4. 将工作表数据存储在一个二维数组或其他适合的地方。
5. 关闭已打开的工作簿。
下面是一个简化的示例代码片段,但这需要进一步修改和完善,例如错误处理和优化性能:
```vba
Sub MergeSheetsIntoArray()
Dim folderPath As String
Dim excelApp As Object
Dim workbook As Object
Dim sheet As Worksheet
Dim dataArray() As Variant
Dim filePath As String
' Set the folder path here
folderPath = "C:\Your\Folder\Path"
' Initialize the array to store data
ReDim dataArray(1 To 1, 1 To 1)
Set excelApp = CreateObject("Excel.Application")
excelApp.Visible = False ' Make Excel run in background
For Each filePath In GetFiles(folderPath, "*.xls*") ' Modify this line with your file filter
If Right(filePath, 4) = ".xlsx" Then
Set workbook = excelApp.Workbooks.Open(filePath)
For Each sheet In workbook.Sheets
' Read and append sheet data (replace 'A1' with appropriate range)
dataArray(UBound(dataArray, 1), UBound(dataArray, 2)) = sheet.Range("A1").Value
' Adjust the dimensions as needed
ReDim Preserve dataArray(1 To UBound(dataArray, 1) + 1, 1 To UBound(dataArray, 2))
Next sheet
workbook.Close SaveChanges:=False ' Close the workbook without saving
End If
Next filePath
' Process or save the combined data as needed
' ...
End Sub
Private Function GetFiles(ByVal rootDir As String, ByVal extFilter As String) As Collection ' Returns a Collection of files matching the extension
Dim collection As New Collection
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim subfolders() As String
subfolders = fso.GetFolder(rootDir).SubFolders
Dim subdir As String
For Each subdir In subfolders
collection.AddJoin "Path", subdir.Path & "\" & extFilter, collection, "Path", rootDir & "\" & extFilter
collection.AddRange fso.GetFiles(subdir.Path, extFilter)
Next subdir
Set collection = Nothing
Set fso = Nothing
Exit Function
Next Function
```
阅读全文