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

时间:2016-07-25 16:18:38

标签: excel vba excel-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

1 个答案:

答案 0 :(得分:1)

代码中有一些东西需要调整才能使其完全像你所描述的文本一样工作。请参阅下面的重构代码。

'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