This is somewhat a continuation on my previous post VBA – Convert XLS to XLSX in which I provided a simple little procedure to upgrade an older xls file to the newer xlsx file format.
I thought to myself, would it be nice to have a more versatile function that could migrate between various other common file formats.
So I set out to take my original function and transform it to enable to user to specify the desired output format and came up with a nice function that enabled anyone to converts Excel compatible files to another Excel compatible format.
Then I said to myself, it must be possible to do something similar for Word and set out to create a function that would enable people to convert file between the various Word compatible formats.
Below are the 2 functions I came up with.
Excel File Format Conversion Function
The following function can be used to convert files between:
- csv -> xlsx
- xls -> xlsx
- xls -> xlsm
- xls -> txt
- xlsx -> txt
- xlsx -> csv
- and so on…
Enum XlFileFormat
'Ref: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/xlfileformat-enumeration-excel
xlAddIn = 18 'Microsoft Excel 97-2003 Add-In *.xla
xlAddIn8 = 18 'Microsoft Excel 97-2003 Add-In *.xla
xlCSV = 6 'CSV *.csv
xlCSVMac = 22 'Macintosh CSV *.csv
xlCSVMSDOS = 24 'MSDOS CSV *.csv
xlCSVWindows = 23 'Windows CSV *.csv
xlCurrentPlatformText = -4158 'Current Platform Text *.txt
xlDBF2 = 7 'Dbase 2 format *.dbf
xlDBF3 = 8 'Dbase 3 format *.dbf
xlDBF4 = 11 'Dbase 4 format *.dbf
xlDIF = 9 'Data Interchange format *.dif
xlExcel12 = 50 'Excel Binary Workbook *.xlsb
xlExcel2 = 16 'Excel version 2.0 (1987) *.xls
xlExcel2FarEast = 27 'Excel version 2.0 far east (1987) *.xls
xlExcel3 = 29 'Excel version 3.0 (1990) *.xls
xlExcel4 = 33 'Excel version 4.0 (1992) *.xls
xlExcel4Workbook = 35 'Excel version 4.0. Workbook format (1992) *.xlw
xlExcel5 = 39 'Excel version 5.0 (1994) *.xls
xlExcel7 = 39 'Excel 95 (version 7.0) *.xls
xlExcel8 = 56 'Excel 97-2003 Workbook *.xls
xlExcel9795 = 43 'Excel version 95 and 97 *.xls
xlHtml = 44 'HTML format *.htm; *.html
xlIntlAddIn = 26 'International Add-In No file extension
xlIntlMacro = 25 'International Macro No file extension
xlOpenDocumentSpreadsheet = 60 'OpenDocument Spreadsheet *.ods
xlOpenXMLAddIn = 55 'Open XML Add-In *.xlam
xlOpenXMLStrictWorkbook = 61 '(&;H3D) Strict Open XML file *.xlsx
xlOpenXMLTemplate = 54 'Open XML Template *.xltx
xlOpenXMLTemplateMacroEnabled = 53 'Open XML Template Macro Enabled *.xltm
xlOpenXMLWorkbook = 51 'Open XML Workbook *.xlsx
xlOpenXMLWorkbookMacroEnabled = 52 'Open XML Workbook Macro Enabled *.xlsm
xlSYLK = 2 'Symbolic Link format *.slk
xlTemplate = 17 'Excel Template format *.xlt
xlTemplate8 = 17 ' Template 8 *.xlt
xlTextMac = 19 'Macintosh Text *.txt
xlTextMSDOS = 21 'MSDOS Text *.txt
xlTextPrinter = 36 'Printer Text *.prn
xlTextWindows = 20 'Windows Text *.txt
xlUnicodeText = 42 'Unicode Text No file extension; *.txt
xlWebArchive = 45 'Web Archive *.mht; *.mhtml
xlWJ2WD1 = 14 'Japanese 1-2-3 *.wj2
xlWJ3 = 40 'Japanese 1-2-3 *.wj3
xlWJ3FJ3 = 41 'Japanese 1-2-3 format *.wj3
xlWK1 = 5 'Lotus 1-2-3 format *.wk1
xlWK1ALL = 31 'Lotus 1-2-3 format *.wk1
xlWK1FMT = 30 'Lotus 1-2-3 format *.wk1
xlWK3 = 15 'Lotus 1-2-3 format *.wk3
xlWK3FM3 = 32 'Lotus 1-2-3 format *.wk3
xlWK4 = 38 'Lotus 1-2-3 format *.wk4
xlWKS = 4 'Lotus 1-2-3 format *.wks
xlWorkbookDefault = 51 'Workbook default *.xlsx
xlWorkbookNormal = -4143 'Workbook normal *.xls
xlWorks2FarEast = 28 'Microsoft Works 2.0 far east format *.wks
xlWQ1 = 34 'Quattro Pro format *.wq1
xlXMLSpreadsheet = 46 'XML Spreadsheet *.xml
End Enum
'---------------------------------------------------------------------------------------
' Procedure : XLS_ConvertFileFormat
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Converts an Excel compatible file format to another format
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Uses Late Binding, so none required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sOrigFile : String - Original file path, name and extension to be converted
' lNewFileFormat: New File format to save the original file as
' bDelOrigFile : True/False - Should the original file be deleted after the conversion
'
' Usage:
' ~~~~~~
' Convert an xls file into a txt file and delete the xls once completed
' Call XLS_ConvertFileFormat("C:TempTest.xls", xlTextWindows)
' Convert an xls file into a xlsx file and NOT delete the xls once completed
' Call XLS_ConvertFileFormat("C:TempTest.xls", False)
' Convert a csv file into a xlsx file and delete the xls once completed
' Call XLS_ConvertFileFormat("C:TempTest.csv", xlWorkbookDefault, True)
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2018-02-27 Initial Release
' 2 2020-12-31 Fixed typo xlDBF24 -> xlDBF4
'---------------------------------------------------------------------------------------
Function XLS_ConvertFileFormat(ByVal sOrigFile As String, _
Optional lNewFileFormat As XlFileFormat = xlOpenXMLWorkbook, _
Optional bDelOrigFile As Boolean = False) As Boolean
'#Const EarlyBind = True 'Use Early Binding, Req. Reference Library
#Const EarlyBind = False 'Use Late Binding
#If EarlyBind = True Then
'Early Binding Declarations
Dim oExcel As Excel.Application
Dim oExcelWrkBk As Excel.Workbook
#Else
'Late Binding Declaration/Constants
Dim oExcel As Object
Dim oExcelWrkBk As Object
#End If
Dim bExcelOpened As Boolean
Dim sOrigFileExt As String
Dim sNewXLSFileExt As String
'Determine the file extension associated with the requested file format
'for properly renaming the output file
Select Case lNewFileFormat
Case xlAddIn, xlAddIn8
sNewFileExt = ".xla"
Case xlCSV, xlCSVMac, xlCSVMSDOS, xlCSVWindows
sNewFileExt = ".csv"
Case xlCurrentPlatformText, xlTextMac, xlTextMSDOS, xlTextWindows, xlUnicodeText
sNewFileExt = ".txt"
Case xlDBF2, xlDBF3, xlDBF4
sNewFileExt = ".dbf"
Case xlDIF
sNewFileExt = ".dif"
Case xlExcel12 = 50 'Excel Binary Workbook *.xlsb
sNewFileExt = ".xlsb"
Case xlExcel2, xlExcel2FarEast, xlExcel3, xlExcel4, xlExcel5, xlExcel7, _
xlExcel8, xlExcel9795, xlWorkbookNormal
sNewFileExt = ".xls"
Case xlExcel4Workbook = 35 'Excel version 4.0. Workbook format (1992) *.xlw
sNewFileExt = ".xlw"
Case xlHtml = 44 'HTML format *.htm; *.html
sNewFileExt = ".html"
Case xlIntlAddIn, xlIntlMacro
sNewFileExt = ""
Case xlOpenDocumentSpreadsheet 'OpenDocument Spreadsheet *.ods
sNewFileExt = ".ods"
Case xlOpenXMLAddIn 'Open XML Add-In *.xlam
sNewFileExt = ".xlam"
Case xlOpenXMLStrictWorkbook, xlOpenXMLWorkbook, xlWorkbookDefault = 51
sNewFileExt = ".xlsx"
Case xlOpenXMLTemplate 'Open XML Template *.xltx
sNewFileExt = ".xltx"
Case xlOpenXMLTemplateMacroEnabled 'Open XML Template Macro Enabled *.xltm
sNewFileExt = ".xltm"
Case xlOpenXMLWorkbookMacroEnabled 'Open XML Workbook Macro Enabled *.xlsm
sNewFileExt = ".xlsm"
Case xlSYLK 'Symbolic Link format *.slk
sNewFileExt = ".slk"
Case xlTemplate, xlTemplate8 ' Template 8 *.xlt
sNewFileExt = ".xlt"
Case xlTextPrinter 'Printer Text *.prn
sNewFileExt = ".prn"
Case xlWebArchive 'Web Archive *.mht; *.mhtml
sNewFileExt = ".mhtml"
Case xlWJ2WD1 'Japanese 1-2-3 *.wj2
sNewFileExt = ".wj2"
Case xlWJ3, xlWJ3FJ3 'Japanese 1-2-3 format *.wj3
sNewFileExt = ".wj3"
Case xlWK1, xlWK1ALL, xlWK1FMT 'Lotus 1-2-3 format *.wk1
sNewFileExt = ".wk1"
Case xlWK3, xlWK3FM3 'Lotus 1-2-3 format *.wk3
sNewFileExt = ".wk3"
Case xlWK4 'Lotus 1-2-3 format *.wk4
sNewFileExt = ".wk4"
Case xlWKS, xlWorks2FarEast 'Lotus 1-2-3 format *.wks
sNewFileExt = ".wks"
Case xlWQ1 'Quattro Pro format *.wq1
sNewFileExt = ".wq1"
Case xlXMLSpreadsheet 'XML Spreadsheet *.xml
sNewFileExt = ".xml"
End Select
'Determine the original file's extension for properly renaming the output file
sOrigFileExt = "." & Right(sOrigFile, Len(sOrigFile) - InStrRev(sOrigFile, "."))
'Start Excel
On Error Resume Next
Set oExcel = GetObject(, "Excel.Application") 'Bind to existing instance of Excel
If Err.Number <> 0 Then 'Could not get instance of Excel, so create a new one
Err.Clear
On Error GoTo Error_Handler
Set oExcel = CreateObject("Excel.Application")
Else 'Excel was already running
bExcelOpened = True
End If
On Error GoTo Error_Handler
oExcel.ScreenUpdating = False
oExcel.Visible = False 'Keep Excel hidden until we are done with our manipulation
Set oExcelWrkBk = oExcel.Workbooks.Open(sOrigFile) 'Open the original file
'Save it as the requested new file format
oExcelWrkBk.SaveAS Replace(sOrigFile, sOrigFileExt, sNewFileExt), lNewFileFormat, , , , False
XLS_ConvertFileFormat = True 'Report back that we managed to save the file in the new format
oExcelWrkBk.Close False 'Close the workbook
If bExcelOpened = False Then
oExcel.Quit 'Quit Excel only if we started it
Else
oExcel.ScreenUpdating = True
oExcel.Visible = True
End If
If bDelOrigFile = True Then Kill (sOrigFile) 'Delete the original file if requested
Error_Handler_Exit:
On Error Resume Next
Set oExcelWrkBk = Nothing
Set oExcel = Nothing
Exit Function
Error_Handler:
MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: XLS_ConvertFileFormat" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occurred!"
oExcel.ScreenUpdating = True
oExcel.Visible = True 'Make excel visible to the user
Resume Error_Handler_Exit
End Function
Word File Format Conversion Function
The following function can be used to convert files between:
- doc -> docx
- docx -> dotx
- docx -> pdf
- docx -> html
- and so on…
Enum WdSaveFormat
'Ref: https://msdn.microsoft.com/en-us/vba/word-vba/articles/wdsaveformat-enumeration-word
wdFormatDocument = 0 'Microsoft Office Word 97 - 2003 binary file format.
wdFormatDOSText = 4 'Microsoft DOS text format. *.txt
wdFormatDOSTextLineBreaks = 5 'Microsoft DOS text with line breaks preserved. *.txt
wdFormatEncodedText = 7 'Encoded text format. *.txt
wdFormatFilteredHTML = 10 'Filtered HTML format.
wdFormatFlatXML = 19 'Open XML file format saved as a single XML file.
' wdFormatFlatXML = 20 'Open XML file format with macros enabled saved as a single XML file.
wdFormatFlatXMLTemplate = 21 'Open XML template format saved as a XML single file.
wdFormatFlatXMLTemplateMacroEnabled = 22 'Open XML template format with macros enabled saved as a single XML file.
wdFormatOpenDocumentText = 23 'OpenDocument Text format. *.odt
wdFormatHTML = 8 'Standard HTML format. *.html
wdFormatRTF = 6 'Rich text format (RTF). *.rtf
wdFormatStrictOpenXMLDocument = 24 'Strict Open XML document format.
wdFormatTemplate = 1 'Word template format.
wdFormatText = 2 'Microsoft Windows text format. *.txt
wdFormatTextLineBreaks = 3 'Windows text format with line breaks preserved. *.txt
wdFormatUnicodeText = 7 'Unicode text format. *.txt
wdFormatWebArchive = 9 'Web archive format.
wdFormatXML = 11 'Extensible Markup Language (XML) format. *.xml
wdFormatDocument97 = 0 'Microsoft Word 97 document format. *.doc
wdFormatDocumentDefault = 16 'Word default document file format. For Word, this is the DOCX format. *.docx
wdFormatPDF = 17 'PDF format. *.pdf
wdFormatTemplate97 = 1 'Word 97 template format.
wdFormatXMLDocument = 12 'XML document format.
wdFormatXMLDocumentMacroEnabled = 13 'XML document format with macros enabled.
wdFormatXMLTemplate = 14 'XML template format.
wdFormatXMLTemplateMacroEnabled = 15 'XML template format with macros enabled.
wdFormatXPS = 18 'XPS format. *.xps
End Enum
'---------------------------------------------------------------------------------------
' Procedure : Word_ConvertFileFormat
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Converts a Word compatible file format to another format
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Uses Late Binding, so none required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sOrigFile : String - Original file path, name and extension to be converted
' lNewFileFormat: New File format to save the original file as
' bDelOrigFile : True/False - Should the original file be deleted after the conversion
'
' Usage:
' ~~~~~~
' Convert a doc file into a docx file but retain the original copy
' Call Word_ConvertFileFormat("C:\Users\Daniel\Documents\Resume.doc", wdFormatPDF)
' Convert a doc file into a docx file and delete the original doc once converted
' Call Word_ConvertFileFormat("C:\Users\Daniel\Documents\Resume.doc", wdFormatPDF, True)
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2018-02-27 Initial Release
'---------------------------------------------------------------------------------------
Function Word_ConvertFileFormat(ByVal sOrigFile As String, _
Optional lNewFileFormat As WdSaveFormat = wdFormatDocumentDefault, _
Optional bDelOrigFile As Boolean = False) As Boolean
'#Const EarlyBind = True 'Use Early Binding, Req. Reference Library
#Const EarlyBind = False 'Use Late Binding
#If EarlyBind = True Then
'Early Binding Declarations
Dim oWord As Word.Application
Dim oDoc As Word.Document
#Else
'Late Binding Declaration/Constants
Dim oWord As Object
Dim oDoc As Object
#End If
Dim bWordOpened As Boolean
Dim sOrigFileExt As String
Dim sNewFileExt As String
'Determine the file extension associated with the requested file format
'for properly renaming the output file
Select Case lNewFileFormat
Case wdFormatDocument
sNewFileExt = "."
Case wdFormatDOSText, wdFormatDOSTextLineBreaks, wdFormatEncodedText, wdFormatOpenDocumentText, wdFormatText, wdFormatTextLineBreaks, wdFormatUnicodeText
sNewFileExt = ".txt"
Case wdFormatFilteredHTML, wdFormatHTML
sNewFileExt = ".html"
Case wdFormatFlatXML, wdFormatXML, wdFormatXMLDocument
sNewFileExt = ".xml"
Case wdFormatFlatXMLTemplate
sNewFileExt = "."
Case wdFormatFlatXMLTemplateMacroEnabled
sNewFileExt = "."
Case wdFormatRTF
sNewFileExt = ".rtf"
Case wdFormatStrictOpenXMLDocument
sNewFileExt = "."
Case wdFormatTemplate
sNewFileExt = "."
Case wdFormatWebArchive
sNewFileExt = "."
Case wdFormatDocument97
sNewFileExt = ".doc"
Case wdFormatDocumentDefault
sNewFileExt = ".docx"
Case wdFormatPDF
sNewFileExt = ".pdf"
Case wdFormatTemplate97
sNewFileExt = "."
Case wdFormatXMLDocumentMacroEnabled
sNewFileExt = ".docm"
Case wdFormatXMLTemplate
sNewFileExt = ".doct"
Case wdFormatXMLTemplateMacroEnabled
sNewFileExt = "."
Case wdFormatXPS
sNewFileExt = ".xps"
End Select
'Determine the original file's extension for properly renaming the output file
sOrigFileExt = "." & Right(sOrigFile, Len(sOrigFile) - InStrRev(sOrigFile, "."))
'Start Excel
On Error Resume Next
Set oWord = GetObject(, "Word.Application") 'Bind to existing instance of Word
If Err.Number <> 0 Then 'Could not get instance of Word, so create a new one
Err.Clear
On Error GoTo Error_Handler
Set oWord = CreateObject("Word.Application")
Else 'Word was already running
bWordOpened = True
End If
On Error GoTo Error_Handler
oWord.Visible = False 'Keep Word hidden until we are done with our manipulation
Set oDoc = oWord.Documents.Open(sOrigFile) 'Open the original file
'Save it as the requested new file format
oDoc.SaveAs2 Replace(sOrigFile, sOrigFileExt, sNewFileExt), lNewFileFormat
Word_ConvertFileFormat = True 'Report back that we managed to save the file in the new format
oDoc.Close False 'Close the document
If bWordOpened = False Then
oWord.Quit 'Quit Word only if we started it
Else
oWord.Visible = True 'Since it was already open, ensure it is visible
End If
If bDelOrigFile = True Then Kill (sOrigFile) 'Delete the original file if requested
Error_Handler_Exit:
On Error Resume Next
Set oDoc = Nothing
Set oWord = Nothing
Exit Function
Error_Handler:
MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: XLS_ConvertFileFormat" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occurred!"
oWord.Visible = True 'Make excel visible to the user
Resume Error_Handler_Exit
End Function
sNewFileExt = "."
entries as applicable.
Thanks for the file format conversion function. Is there any way to reference a excel worksheet instead of a workbook?
I’m afraid I do not understand the question. You can only convert an entire Workbook. You can convert a single sheet in a workbook and leave the other sheets in the original format.
As for automation, yes, you can easily work with a specific worksheet by doing something along the lines of:
Dim oExcelWrSht As Object Set oExcelWrSht = oExcelWrkBk.Sheets(1) 'Or Set oExcelWrSht = oExcelWrkBk.Sheets("SheetName")Well I’m new to this, could you show an example of how to use it?
Just follow the function arguments and usage examples.
Call XLS_ConvertFileFormat("C:\temp\book1.xls", xlCSV)This will effectively convert (save as) the Excel file C:\temp\book1.xls as a csv in the same folder as the original file, so C:\temp\book1.csv
Akash,
I believe there is a small typo.
in the xl case statement, you reference xlDBF24 , when I believe you meant to type xlDBF4 instead.
Thank you for writing and sharing this.
I will be testing it out this weekend to see how well it works and whether or not I can use this for the problem du jour. 🙂
Thank you for pointing that out, I’ve updated the code.
Is it possible to use this to bulk convert XLSX to XLTX?
I don’t see why not simply specify xlOpenXMLTemplate as the lNewFileFormat input variable. As always, test first on backed up files before putting into production.
Hi Daniel. Thanks and looks very useful! Works fine with the exception of the DBF formats. This one works fine:
Call XLS_ConvertFileFormat(“c:\_aa\All_08.dbf.xlsx”, xlCSV)
and this one drops an error
Call XLS_ConvertFileFormat(“c:\_aa\All_08.dbf.xlsx”, xlDBF3)
Any suggestions? Thx Peter
What error?
That said, when I look at the SaveAs dialog, as a reference, dbf doesn’t even appear in the list anymore. So I’m thinking it is no longer possible on certain versions. It would seem that ability ended in Excel 2003.
I suppose you could write your own export routine. I’ll see if I can do some digging. I’m wondering if the easiest solution might not be to push the data to Access and export it form there, but as I say, I need to look into the details further.
how do i convert and keep the newly created file open?
ex – have xls file open with leading zeroes – need macro to keep leading zeroes and save/open nex csv(excel) open?
Hello,
wow, I’m very impressed about your 2 vba solutions to convert file form one format to another
A) I have 2 questions about your vba codes:
– I would like add the following options to the vba code
1) After starting the macro, I want the presend an input-box for the user the select the file (over browsing)
2) Then the user has to choose the destination format (over a list-box with the new format)
3) Then the user has to select to select if he want to delete the source (Yes or No)
How can I change the vba code?
P.S. Same for the vba for Word conversion tasks
B) Then, I have the following idea
– I would like to have the opportunity to select a folder as source (browse for select a folder)
– Then the user select the destination format as output (over list-box)
– Then the user has to select to select if he want to delete the source files (Yes or No)
Kind regards
Pascal Bilat
Your best bet is probably to create a custom user from for the user to make their selections and then initialize the process. I’d urge you to post your question in a VBA programming forum where fellow developers can help you and have proper back and forth with you.
Give all the details possible including which version and bitness of Office/Excel you are working with.
Good luck with your project.
I’ve quickly built a sample for you to build from. It should get you well on your way.
https://1drv.ms/u/s!AjYnefG2siYSjRDsuYOvqLQc–wR?e=favStv
Hello
Sorry, but how to I add the vba code in Excel? When I start the macro, the macro environment is empty?
Best regards,
Pascal Bilat
You need to insert a new standard module and go from there.
Hi I am completely new in VBA. I am stuck with some SLK files and my organization has restricted access to slk files. I have copies all the above code inside “New module” and then entered the following command in excel cell: =XLS_ConvertFileFormat(“C:\Users\…filename.slk”) but its returning me the error #NAME?
Cane you please help me how do i utilize this code to convert slk file to any other excel format? Thank you
Hi Daniel,
I think I’m doing something wrong. I have copied the code into a new module in a new excel file. I have then created a macro button and gone right click > assign macro > pasted XLS_ConvertFileFormat into the field. Then hit the button and get a window saying Argument not optional. What am I doing wrong?
You have to follow the usage examples:
Call XLS_ConvertFileFormat(“C:TempTest.xls”, xlTextWindows)
Where you have to provide the necessary input arguments to the function:
sOrigFile : String – Original file path, name and extension to be converted
lNewFileFormat: New File format to save the original file as
bDelOrigFile : True/False – Should the original file be deleted after the conversion