File format in excel vba

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Workbook.FileFormat property (Excel)

vbaxl10.chm199100

vbaxl10.chm199100

excel

Excel.Workbook.FileFormat

ef722c3c-90ea-9810-b853-a3fff19d5c60

05/29/2019

medium

Workbook.FileFormat property (Excel)

Returns the file format and/or type of the workbook. Read-only XlFileFormat.

Syntax

expression.FileFormat

expression A variable that represents a Workbook object.

Remarks

Some of these constants may not be available to you, depending on the language support (U.S. English, for example) that you’ve selected or installed.

Example

This example saves the active workbook in Normal file format if its current file format is Excel 97/95.

If ActiveWorkbook.FileFormat = xlExcel9795 Then 
 ActiveWorkbook.SaveAs fileFormat:=xlExcel12 
End If

[!includeSupport and feedback]

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:UsersDanielDocumentsResume.doc", wdFormatPDF)
' Convert a doc file into a docx file and delete the original doc once converted
'   Call Word_ConvertFileFormat("C:UsersDanielDocumentsResume.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

Missing File Extensions

Unlike the Excel function, the Word function is currently missing some of the file extensions. I created the general framework, but could not easily find the associated file extensions to some of the file format. You need only complete the missing entry and it will work. So simply update the

sNewFileExt = "."

entries as applicable.

You can VBA Read file binary or text data using a couple of different approaches in Excel. VBA provides you a set of native statements like Open to open and ready files. However in this article aside from showing you these native approaches to reading files using Excel Macros you can read CSV files and other structured data schemas using Jet.OLEDB driver, Microsoft Queries or also the FileSystemObject.

Text/binary files are common ways of storing data as opposed to databases or regular Excel files. Looking at various resources I missed a single resource which would demonstrate the various methods for PROPERLY reading files in VBA.

It is important to remember that you shouldn’t read all files using the same approach. Be aware of the structure of the file. If it is a structured CSV use the ADODB connection, if you need to read only a couple of rows read the file row by row or by chunks, else read the whole file. If you want performance – always select the right approach.

Reading text files in VBA

VBA Read text files (line by line)

To read an entire text file line by line use the code below.

Dim fileName As String, textData As String, textRow As String, fileNo As Integer
fileName = "C:text.txt"
fileNo = FreeFile 'Get first free file number  
    
Open fileName For Input As #fileNo
Do While Not EOF(fileNo)
   Line Input #fileNo, textRow
   textData = textData & textRow
Loop
Close #fileNo

VBA Read text files (read whole file)

To read an entire text file in one go (not line by line) use the code below.a

Dim fileName As String, textData As String, fileNo As Integer
fileName = "C:text.txt"
fileNo = FreeFile 'Get first free file number   
 
Open fileName For Input As #fileNo
textData = Input$(LOF(fileNo), fileNo)
Close #fileNo

VBA Read specific number of lines from a text file

In cases when you want to read specific lines from a text file you can adapt the line by line read code as below. It allows you to read a certain number of lines (noLines) from a text file from a specific start line number (sLine). If you set noLines to 0 it will read all lines till end of the file.

Dim fileName As String, textData As String, textRow As String, fileNo As Integer
Dim lineCounter as Long, sLine as Long, noLines as Long

fileName = "C:text.txt"

sLine = 20 'number of the first line you want to read
noLines = 100 'number of lines you want to read

fileNo = FreeFile 
Open fileName For Input As #fileNo
Do While Not EOF(fileNo)
  Line Input #fileNo, textRow
  If lineCount >= sLine and ((noLines > 0 and lineCount < noLines + sLine) or noLines = 0) then
    textData = textData &amp; textRow
  End If
  lineCount = lineCount + 1   
Loop
Close #fileNo

Reading CSV files in VBA

Reading CSV files (read whole file and process each row)

Reading a text file line by line into a string:

'Assuming file looks like this. File path: C:test.csv
'"Col1", "Col2", "Col3"
'1     , 2     , 3

directory = "C:"
fileName = "test.csv" 'Assuming test.csv is in C: directory
Set rs = CreateObject("ADODB.Recordset")
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & ";" _
& "Extended Properties=""text;HDR=Yes;FMT=Delimited"";"
strSQL = "SELECT * FROM " & fileName 
rs.Open strSQL, strcon, 3, 3
rs.MoveFirst
Do
   col1 = rs("Col1")
   col2 = rs("Col2")
   col3 = rs("Col3")
   rs.MoveNext
Loop Until rs.EOF

Reading CSV files (whole file to Worksheet)

Read whole file to an Excel Worksheet:

Dim ws as Worksheet, destRng as Range, fileName as String
fileName = "C:text.txt"
Set destRng = Range("A1")
Set ws = ActiveSheet
With ws.QueryTables.Add(Connection:= "TEXT;" & fileName & "", Destination:=destRng)
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 852
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    'Select your delimiter - selected below for Comma
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileTrailingMinusNumbers = True
    'This will refresh the query
End With

To refresh the CSV upload (in case the CSV was updated) simply run:

  
ws.QueryTables.Refresh BackgroundQuery:=False

Reading binary files in VBA

Dim fileName As String, fileNo As Integer, intVar As Integer
fileName = "C:text.bin"
fileNo = FreeFile

Open fileName For Binary Lock Read As #fileNo
Get #fileNo, , intVar
Close #fileNo

With Binary files often you will be using objects which are not of fixed byte length like Integers. For example you would want to read Strings from binary files together with other data types. In such cases use the Type object data type when writing to a file. Learn more here.
Below a simple example of reading a file to which a Type data type was saved to, including an Integer and String.

Type TestType
    intVar As Integer
    strVar As String
End Type

Sub ReadBinary()
    Dim fileName As String, fileNo As Integer, testVar As TestType
    fileName = "C:test.bin"

    fileNo = FreeFile
    Open fileName For Binary Lock Read As #fileNo
    Get #fileNo, , testVar
    Debug.Print testVar.intVar 'Print the Integer
    Debug.Print testVar.strVar 'Print the String
    Close #fileNo
End Sub

Reading XML files in VBA

XML files are basically text files which follow the XML taxonomy. You can try to read and process XML files similarly as text files shown above. However, given you will probably want to extract specific XML tag or attribute information I suggest reading my dedicated article below.

Functions needed to read files in VBA

Function Description
Open [path_to_file] For [Mode] [Access] [Lock] As [long_variable] Opens the file for read/write and returns the # file number (needs to be type of long) into long_variable
More info here. Parameters below:

  • Mode – Append, Binary, Input, Output, or Random
  • Access optional. Read, Write, or Read Write
  • Lock optional. Shared, Lock Read, Lock Write, and Lock Read Write.
Close Closes the file using the # file number.
More info here.
FreeFile Get next free file number available for the Open statement / FileOpen function. Using this function is important especially when operating on multiple files simultaneously.
More info here.
BOF(fileNumber) Returns true if you are at the beginning of the file described by the file number.
More info here.
EOF(fileNumber) Returns true if you have reached the end of the file described by the file number. More info here.
Loc(fileNumber) Returns the current read/write position within an open file. More info here.
LOF(fileNumber) Returns the size in bytes of the file represented by the file number. More info here.

Above functions allow native upload of file data. However for more complicated scenario you will probably go for the FileSystemObject.

VBA Read File Summary

Reading files in VBA is not hard and requires just a few lines of code usually. It is, however, important to use the appropriate approach to read a file in VBA. Not all files need to be read line-by-line which is usually inefficient. Equally so you need not always read the entire file if you just need the first few / last rows. Working with XML files is also not a challenge if you read through my post on how to work with XML files.

Want to Write to files instead?

If you are looking to write to files instead using VBA, read my article on how to write to files using VBA.

  • #1

I am trying to make a File SaveAs macro that can save in different formats.

This Works:

Code:

ActiveWorkbook.SaveAs Filename:="C:UsersChrisDesktopBook1.xlsx", _
        FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

This Doesn’t Work:

Code:

FileFormat = "xlOpenXMLWorkbook"  
        ActiveWorkbook.SaveAs Filename:="C:UsersChrisDesktopBook1.xlsx", _
        FileFormat:=FileFormat, CreateBackup:=False

I’m guessing its because I am setting my FileFormat variable as a string but I am not sure how else to go about making this code variable.

When I try the following code, I get an error stating that an object is required

Code:

Set FileFormat = xlOpenXMLWorkbook


Text files are a common source for storing and transporting information.

This topic will address access, key functions and ways to import and export this data with VBA.


VBA Open

To perform tasks with a text file in VBA you must first access it. We will do this through instruction Open.

Open requires parameters for:

  • O pathname (directory or folder, and drive)
  • O mode of access (Append, Binary, Input, Output, or Random)
  • A filenumber of access (represented by a unique number per file)
    Open PathName For Mode As #FileNumber.

Each of these parameters will be detailed below.


File’s Path

You can assign the path name in two ways:

    PathName = "C:testdatabase.txt" 'Directly through folders path

    PathName = Application.GetOpenFilename() 'Through a dialog box selecting the file

The first form is used when the path does not change constantly. The second gives freedom, at each execution, to choose a different path.

Both of these forms will result in PathName associated with a String of the file location.


Mode

The mode must be one of the following commands:

Output — Used to write Excel content to the text file

Input — Used to read the file

Append — Used to add content to a file

Binary — Used to read and write data in a byte format

Random — Used to place characters of defined size

The focus of this tutorial will be only on: Input (import) and Output (export).


File Number

Each open file must contain a numbering, a number between 1 and 511 preceded by a hashtag #. Normally the numbering starts at #1 and follows successively #2…

Use the FreeFile statement to get the next available file number. If none is in use, FreeFile() will return 1.


Testing Open Instruction

The following code will access the file you selected with Application.GetOpenFilename()

Sub OpenTeste()

    Dim PathName As String

    PathName = Application.GetOpenFilename()
    'Opens the dialog box to select the file

    'Notice that PathName will be a path String E.g. "C:..."

    Dim FileNumber As Integer

    FileNumber  = FreeFile() 'Assigns the first available file number (E.g.: #1)

    Open PathName For Input As #FileNumber

    Close #FileNumber  'Closes the file (the number in FileNumber can be reused)
End Sub

Despite access, no information was imported or exported. To carry out these actions, we will need the help of the functions Input and Output respectively.


Import Text File

To import content from a text file into Excel we will use an example file called «database.txt» and the function Input:

Database TXT

Sub SimpleImport()

    Dim PathName As String

    PathName = Application.GetOpenFilename()
    'Opens the dialog box to select the file

    'Notice that PathName will be a path String E.g. "C:...database.txt"

    Dim FileNumber As Integer

    Open PathName For Input As #1 'File will be associated with the #1

    FirstCharacter = Input(1, #1) 'Collect 1 character from file # 1
    SecondCharacter = Input(1, #1) 'Collect 1 more character, this being the next one (the 2nd in this case)

    MsgBox FirstCharacter
    MsgBox SecondCharacter

    Close #1 'Close the file (number #1 to be reused)
End Sub

MsgBox A

MsgBox q

To collect all the characters at once we can use the LOF function:

Sub LOFimport()

    Dim PathName As String

    PathName = Application.GetOpenFilename()
    'Opens the dialog box to select the file

    'Notice that PathName will be a path String E.g. "C:...database.txt"

    Dim FileNumber As Integer

    Open PathName For Input As #1 'File will be associated with the #1

    MsgBox LOF(1)  'Total number of characters in file # 1

    Allcharacters = Input(LOF(1), #1) 'Collect all characters from file # 1

    MsgBox Allcharacters

    Close #1 'Close the file (number #1 to be reused)
End Sub

LOF returns the number of bytes of the file opened with Open. Because this is a text file, each byte is one character. Thus, the number of bytes will equal the number of characters.

To import the data into spreadsheet we can use the following code:

Sub TextImport ()
    Dim PathName As String
    Dim FileNumber As Integer
    Dim Textdata As String
    Dim BreakingLine as Variant
    Dim Lastline as Integer
    Dim Firstline as Integer

    'Opens the dialog box to select the file
    PathName = Application.GetOpenFilename()
    'Or enter a path with PathName = "C:FILE_LOCATIONdatabase.txt"

    FileNumber = FreeFile() 'Assigns the first available file number (E.g.: #1)

    Open PathName For Input As #FileNumber 'Open file in read mode

    'Copy the contents to Worksheet ---
    Textdata = Input(LOF(FileNumber), FileNumber) 'Loads all file contents into variable
    BreakingLine = Split(Textdata, vbCrLf) 'Creates a vector with each line of the file 
    Lastline = UBound(BreakingLine) 'Determines the last line of the vector
    Firstline = LBound(BreakingLine) 'Determines the first line of the vector
    'Transpose the vectors into the worksheet
    Range("A1").Resize((Lastline) - (Firstline) + 1).Value = Application.Transpose(BreakingLine)
    '----------------------------------
    Close #FileNumber 'Closes the file (the number in FileNumber can be reused)
End Sub

vbCrLf is a non-visible character CrLf indicates a line break in the file.


Main Functions Related to Open

Function Description
FreeFile Returns the next available number for the Open statement. Important when working with multiple files.
BOF Returns True if it is at the beginning of the defined #filenumber.
EOF Returns True if it has finished reading the defined #filenumber.
LOF Returns the size in bytes of the defined #filenumber.
Loc Returns the current read and write position for the Open.

BOF and EOF assist in building Loops when you want to work character by character, or line by line.

Character per character

    'Collect one by one
    Characters = Input(1, #1) 'Collect 1 character from file # 1
    Characters = Characters & Input(1, #1) 'Collect 1 more character, this being the next
    Characters = Characters & Input(1, #1) 'Collect 1 more character, this being the next
    '...

Loop with EOF support

    'Loop with EOF support
    Characters = ""
    Do While Not EOF(1)
        Characters = Characters & Input(1, #1)
    Loop

Loop with BOF support

    'Loop with BOF support
    Do While BOF(1)
        Characters = Characters & Input(1, #1)
    Loop

Export Text File

To export worksheet content to a text file:

Sub TextExport()

    Dim LastRow As Long
    Dim LastColumn As Long
    Dim NewFile As String
    Dim FileNumber As Integer
    Dim CellData As Variant

    FileNumber = FreeFile ' Assigns the first available file number (E.g.: #1)

    'Determines the last row of the worksheet with data
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row

    'Determines the last column of the worksheet with data
    LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
    NewFile = "C:TestExport.txt" 'Use an existing folder

    'Exports the data from the worksheet to the created file
    Open NewFile For Output As #FileNumber 
    For i = 1 To LastRow
        For j = 1 To LastColumn
            If j = LastColumn Then
                CellData = CellData & Cells(i, j).Value
            Else
                CellData = CellData & Cells(i, j).Value & " "
            End If
        Next j
        Print #FileNumber, CellData
        CellData = ""
    Next i
    Close #FileNumber 'Saves and closes the text file with the data
End Sub

An error will occur if the folder you are saving the file does not already exist.


CSV File

A .csv file (Comma Separated Values) is, as the name suggests, a text file in which the items in each row are separated by commas, delimiting what should go in each column.

CSV Example

It is a very common type of file, and since each line refers several times to multiple columns, it may require a treatment with loops and functions, such as BOF and EOF.


Import CSV File

For ease of import, the Line Input instruction (which works line by line), rather than just Input (which works character by character).

Sub OpenTextToCSV()
    Dim PathName As String
    Dim FileNumber As Integer
    Dim FileRow As String
    Dim RowItem As Variant
    Dim LastRow As Long

    'Opens the dialog box to select the file
    PathName = Application.GetOpenFilename()
    'Or enter a path Ex: PathName = "C:testdatabase.txt"

    FileNumber = FreeFile ' Assigns the first available file number (Ex: #1)

    Open PathName For Input As #FileNumber 'Opens the file in read mode

    Do Until EOF(FileNumber)
        Line Input #FileNumber, FileRow
            RowItem = Split(FileRow, ", ")
            i = i + 1
            LastRow = UBound(RowItem)
            For j = 1 To LastRow + 1
                Cells(i, j).Value = RowItem(j - 1)
            Next
    Loop

    Close #FileNumber
End Sub

Export CSV File

Similar to exporting text, however mandatory the use of «, « in the separation of elements.

Sub SaveTextToCSV()

    Dim LastRow As Long
    Dim LastColumn As Long
    Dim NewFile As String
    Dim FileNumber As Integer
    Dim CellData As Variant

    FileNumber = FreeFile ' Assigns the first available file number (Ex: #1)

    'Determines the last row of the worksheet with data
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row

    'Determines the last column of the worksheet with data
    LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
    NewFile = "C:TestExport.csv" 'Use an existing folder

    'Exports the data from the worksheet to the created file
    Open NewFile For Output As #FileNumber
        For i = 1 To LastRow
            For j = 1 To LastColumn
                If j = LastColumn Then
                    CellData = CellData & Cells(i, j).Value
                Else
                    CellData = CellData & Cells(i, j).Value & ", "
                End If
            Next j
            Print #FileNumber, CellData
            CellData = ""
        Next i
    Close #FileNumber 'Saves and closes the text file with the data
End Sub

An error will occur if the folder you are saving the file does not already exist.



SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

© 2023 SuperExcelVBA | ABOUT

Protected by Copyscape

Понравилась статья? Поделить с друзьями:
  • File format for word document
  • File extensions for excel files
  • File extension for excel files
  • File embedding in word
  • File embedded in word