【发布时间】:2018-04-08 13:49:39
【问题描述】:
试图弄清楚如何将选定文件夹中的所有 excel 文件保存为启用宏的工作簿。如果可能的话,我只想保存启用宏的工作簿来替换文件夹中的所有 excel 文件。目前我只有在文件夹中打开一个 excel 文件的代码 - 我不知道如何将打开的工作簿保存为启用宏的工作簿,更不用说遍历整个文件夹了。这是我拥有的代码,如果我使用 if 语句而不是 do while 循环来打开一个文件,它适用于一个文件。它说 do while 循环中的 file = dir 有错误:
Sub SaveAllAsMacroWkbks()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String, macFile As String
Dim myExtension As String, macExt As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
macExt = "*.xlsxm"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
macFile = Dir(myPath & macExt)
'Loop through each Excel file in folder
Do While myFile <> ""
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'wb.saveAs FileName:=macFile, FileFormat:=52
'wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
【问题讨论】: