【发布时间】:2021-04-13 14:43:42
【问题描述】:
我有一个文件夹,其中包含我制作的脚本中的大约 500-600 个 excel 文件,其中文件名最终是这样的
101a12345.xlsx
101a67899.xlsx
102a12345.xlsx
102a78999.xlsx
文件名遵循该模式、101a、102a 等。我想要做的是将基于该模式的文件合并到 1 个 excel 文件中。因此,101a12345.xlsx 和 101a67899.xlsx 应合并为 101aMaster.xlsx。所有的excel文件都是单张的。
我在这里找到了我正在尝试实现的示例代码:How to merge multiple workbooks into one based on workbooks names
取自以上链接:
Sub test(sourceFolder As String, destinationFolder As String)
Const TO_DELETE_SHEET_NAME As String = "toBeDeleted"
'------------------------------------------------------------------
Dim settingSheetsNumber As Integer
Dim settingDisplayAlerts As Boolean
Dim dict As Object
Dim wkbSource As Excel.Workbook
Dim wks As Excel.Worksheet
Dim filepath As String
Dim code As String * 4
Dim wkbDestination As Excel.Workbook
Dim varKey As Variant
'------------------------------------------------------------------
'Change [SheetsInNewWorkbook] setting of Excel.Application object to
'create new workbooks with a single sheet only.
With Excel.Application
settingDisplayAlerts = .DisplayAlerts
settingSheetsNumber = .SheetsInNewWorkbook
.SheetsInNewWorkbook = 1
.DisplayAlerts = False
End With
Set dict = VBA.CreateObject("Scripting.Dictionary")
filepath = Dir(sourceFolder)
'Loop through each Excel file in folder
Do While filepath <> ""
If VBA.Right$(filepath, 5) = ".xlsx" Then
Set wkbSource = Excel.Workbooks.Open(sourceFolder & filepath)
Set wks = wkbSource.Worksheets(1)
code = VBA.Left$(wkbSource.Name, 4)
'If this code doesn't exist in the dictionary yet, add it.
If Not dict.exists(code) Then
Set wkbDestination = Excel.Workbooks.Add
wkbDestination.Worksheets(1).Name = TO_DELETE_SHEET_NAME
Call dict.Add(code, wkbDestination)
Else
Set wkbDestination = dict.Item(code)
End If
Call wks.Copy(Before:=wkbDestination.Worksheets(1))
wkbDestination.Worksheets(1).Name = VBA.Mid$(filepath, 6)
Call wkbSource.Close(False)
End If
filepath = Dir
Loop
'Save newly created files.
For Each varKey In dict.keys
Set wkbDestination = dict.Item(varKey)
'Remove empty sheet.
Set wks = Nothing
On Error Resume Next
Set wks = wkbDestination.Worksheets(TO_DELETE_SHEET_NAME)
On Error GoTo 0
If Not wks Is Nothing Then wks.Delete
Call wkbDestination.SaveAs(Filename:=destinationFolder & varKey & ".xlsx")
Next varKey
'Restore Excel.Application settings.
With Excel.Application
.DisplayAlerts = settingDisplayAlerts
.SheetsInNewWorkbook = settingSheetsNumber
End With
End Sub
但是,此代码会打开所有工作簿,并且在大约 60-70 个打开的 excel 文件时我收到一个错误:运行时错误“1004”-对象“工作簿”的“打开”方法失败。
有没有办法让这段代码工作?
Excel 版本是 pro plus 2016。
【问题讨论】:
-
我认为您的问题是您在第一个 Do 循环中打开了两个工作簿,但只关闭了其中一个。如果你解决了这个问题,代码可能不会出错,但我怀疑它离你想要它做的事情还有很长的路要走。
标签: excel vba runtime-error