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