[英]File Format Error When Batch convert .xls to .xlsx with VBA without opening the workbooks
I have hundreds of XLS files I need converted to XLSX.我有数百个 XLS 文件需要转换为 XLSX。
I found this old thread with the same title and the code provided converts the files to XLSX but corrupts them.我找到了这个具有相同标题的旧线程,提供的代码将文件转换为 XLSX 但会损坏它们。
My understanding is, this code renames the file with the proper xlsx extension but does not change the file format.我的理解是,此代码使用正确的 xlsx 扩展名重命名文件,但不会更改文件格式。
I am under the impression I need to make the file format FileFormat:=51我的印象是我需要制作文件格式FileFormat:=51
I tried adding ", FileFormat:=51" to the name but that did not seem to work.我尝试在名称中添加“, FileFormat:=51”,但这似乎不起作用。
Any suggestions on how I can change the FileFormat to 51?关于如何将 FileFormat 更改为 51 的任何建议?
Thank you谢谢
Love you all爱你们
Sub ChangeFileFormat_V1()
Dim strCurrentFileExt As String
Dim strNewFileExt As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As File 'Object
Dim xlFile As Workbook
Dim strNewName As String
Dim strFolderPath As String
strCurrentFileExt = ".xls"
strNewFileExt = ".xlsx"
strFolderPath = "C:\Users\Scorpio\Desktop\New folder"
If Right(strFolderPath, 1) <> "\" Then
strFolderPath = strFolderPath & "\"
End If
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.getfolder(strFolderPath)
For Each objFile In objFolder.Files
strNewName = objFile.Name
If Right(strNewName, Len(strCurrentFileExt)) = strCurrentFileExt Then
strNewName = Replace(strNewName, strCurrentFileExt, strNewFileExt)
Application.DisplayAlerts = False
objFile.Name = strNewName
Application.DisplayAlerts = True
End If
Next objFile
``ClearMemory:
strCurrentFileExt = vbNullString
strNewFileExt = vbNullString
Set objFSO = Nothing
Set objFolder = Nothing
Set objFile = Nothing
Set xlFile = Nothing
strNewName = vbNullString
strFolderPath = vbNullString
End Sub
Like I mentioned in the comment, you cannot just change the extention and expect it to work.就像我在评论中提到的那样,您不能只是更改扩展名并期望它起作用。 You are supposed to open the file and do a
.SaveAs NewFilename,Fileformat
for each one of them.您应该打开文件并为每个文件执行
.SaveAs NewFilename,Fileformat
。
Is this what you are trying?这是你正在尝试的吗? ( Untested )
(未经测试)
Sub Sample()
Dim strFolderPath As String
Dim StrFile As String
Dim NewFilename As String
Dim wb As Workbook
'~~> Set your folder here
strFolderPath = "C:\Users\Scorpio\Desktop\New folder\"
'~~> Loop through all the xls files in the folder
StrFile = Dir(strFolderPath & "*.xls")
Do While Len(StrFile) > 0
'~~> Get file name without extension
NewFilename = Left(StrFile, (InStrRev(StrFile, ".", -1, vbTextCompare) - 1))
Set wb = Workbooks.Open(strFolderPath & StrFile)
wb.SaveAs NewFilename & ".xlsx", FileFormat:=xlOpenXMLWorkbook
DoEvents
wb.Close (False)
StrFile = Dir
Loop
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.