VBA代码来更改文件夹中多个文件的文件格式

以下代码将保存为.xml的多个文件的文件格式更改为.xlsx文件。 它只是打开一个特定的文件夹中的文件和“另存为” .xlsx 。 但是我不知道如何使它运行在我的目标文件夹中的所有文件。 截至目前它只是指向文件夹中的第一个文件。

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 

代码中有几件事情需要调整才能使其与您所描述的文本完全一致。 请参阅下面的重构代码。

 'Target File Extension (must include wildcard "*") myExtension = "*.xml" `- since you want to open xml files to save as xlsx 

然后改变

  'Change the format ActiveWorkbook.SaveAs Filename:= _ "S:\Xyz\abc.xlsx" _ , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False 

  'Change the format wb.SaveAs Filename:= wb.Path & "\" Replace(wb.Name,".xml",".xlsx"), _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False 

然后删除这个: End With