我制作了一个代码来帮助我快速保存一些文件,这些文件在optimasing一个在线例子中。当我以xls格式保存文件时,一切看起来都很正常,但是当我在xlsx中执行并尝试打开保存的文件时,会出现一个错误,告诉我格式已损坏。
开头的xls中的所有文件
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim wb As Workbook
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
'security biass
If Worksheets("atualizador").Range("H6") <> "x" Or Worksheets("atualizador").Range("H7") <> "x" Then
Exit Sub
End If
'start folder
myPath = "C:\Users\anna.costa\Downloads\Dados\"
'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)
'copy Worksheet's and rename
If Right(myFile, 5) <> ")" Then
Select Case Left(myFile, 1)
Case "V"
wb.SaveAs ("C:\Users\anna.costa\Desktop\Dados_FIPE\ANBIMA\VNA\" & setnameVNA(myFile) & ".xlsx")
wb.Close SaveChanges:=False
Case "m"
wb.SaveCopyAs ("C:\Users\anna.costa\Desktop\Dados_FIPE\ANBIMA\TÍTULO_PÚBLICO\" & setnameTP(myFile) & ".xls")
wb.Close SaveChanges:=False
Case "C"
wb.SaveCopyAs ("C:\Users\anna.costa\Desktop\Dados_FIPE\ANBIMA\ETTJ\" & setnameETTJ(myFile) & ".xlsx")
wb.Close SaveChanges:=False
End Select
End If
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:2)
您正在尝试打开xls
文件并将其另存为xlsx
文件,而不进行任何转换。要将文件正确转换为xlsx
,您需要包含正确的FileFormat
:
wb.SaveAs "C:\Users\anna.costa\Desktop\Dados_FIPE\ANBIMA\ETTJ\" & setnameETTJ(myFile) & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, AccessMode:=xlExclusive, ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
wb.Close SaveChanges:=False
答案 1 :(得分:0)
我遇到了类似的情况,我所做的就是这个
Set WBDesiredToConvert = ThisWorkbook
WBDesiredToConvert.SaveAs ThisWorkbook.Path & "\" & "MacroEnabled", 52