0
以下代码将多个文件的文件格式更改为.xml更改为.xlsx文件。它只是打开特定文件夹中的文件并“另存为”.xlsx。但是我不知道如何让它在我的目标文件夹中的所有文件上运行。截至目前它只是指向文件夹中的第一个文件。更改文件夹中多个文件的文件格式的VBA代码
Sub m_convertformat()
'
' m_convertformat Macro
'
'
Dim wb As Workbook
Dim sht As Worksheet
Dim myPath As String
Dim myFile As String
Dim myExtension 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"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Change the format
ActiveWorkbook.SaveAs Filename:= _
"S:\Xyz\abc.xlsx" _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End With
'Save and Close Workbook
wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
End Sub
参见[使用FileSystemObject的目录中枚举文件(http://stackoverflow.com/documentation/vba/990/scripting-filesystemobject/9507/enumerate-files-in-a-directory-using-filesystemobject)或[Loop th粗略的文件在使用VBA的文件夹?](http://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba)(可能还有一堆其他的)。 – Comintern
我相信这是你设置'myFile'的方式。试试'myFile = Dir(myPath)'并添加一个'If()'语句来查看它是否是'myExtension'类型文件。现在,变成'myFile = Dir(C:\ Users \ Me \ myFileFolder \ .xls)'? @共产国际第二个链接的答案应该指导你。 – BruceWayne