1

here is a question for you, say I have a procedure that reads a text file then it does some processing to it, in order to read that text file I'm gonna use the File System Object method. and the syntax for it is this object.OpenTextFile(filename[, iomode[, create[, format]]]), now, the optional parameter formatis used to read the text file in three Encoding options:

  • system default
  • ASCII
  • UNICODE

my question:

How Do i test the file Encoding beforehand, So that i can choose the right Format?

here is a sample code that I'm using as part of a project, in this function the user passes a file type of either (txt, docx, doc, rtf) if the type is (rtf, doc, docx) the actual file object (document) will be returned and if the file is a text file, it will be read line by line into a new document and return that new document :

Sub test()
    ReadTxtOrDocIntoDocument_1 ("C:\Test.txt")
End Sub

Function ReadTxtOrDocIntoDocument_1(ByVal DocPath As String) As Document
'in this func we only create a new doc for the text file
'because the opening of a text file in word is messy
'if the file is supported then just open it for further processing
'======================================================
    If Not DocPath = "" Then    'check if the path is not empty
        'make sure one temp doc exists throughout the processing time
        Dim fileExt As String    'stores the file extension of the list file
        fileExt = Right(DocPath, Len(DocPath) - InStrRev(DocPath, "."))
        '======================================================
        'let's check if the file is text or doc
        Select Case LCase(fileExt)
        Case "docx"
            Set ReadTxtOrDocIntoDocument_1 = Documents.Open(DocPath)
        Case "doc"
            Set ReadTxtOrDocIntoDocument_1 = Documents.Open(DocPath)
        Case "rtf"
            Set ReadTxtOrDocIntoDocument_1 = Documents.Open(DocPath)
        Case "txt"
            'a doc that recieves the list words for comparison
            Set ReadTxtOrDocIntoDocument_1 = Documents.Add
            '======================================================
            Dim FSO As Object
            Set FSO = CreateObject("Scripting.FileSystemObject")
            '======================================================
            Const ForReading = 1
            Const OpenAsUNICODE = -1
            Const OpenAsSystemDefault = -2
            '======================================================
            Dim TxtFile As Object
            Set TxtFile = FSO.OpenTextFile(DocPath, ForReading, , OpenAsSystemDefault)
            Dim ThisLine As String
            Dim i As Integer
            i = 0
            '======================================================
            Do Until (TxtFile.AtEndOfStream)    'keep looping until end of file
                ThisLine = TxtFile.ReadLine
                'go to doc starting point
                ReadTxtOrDocIntoDocument_1.Range.MoveStart unit:=wdStory, Count:=1
                'insert text after the begining
                ReadTxtOrDocIntoDocument_1.Range.InsertAfter ThisLine
                'go to end of the doc
                ReadTxtOrDocIntoDocument_1.Range.MoveEnd unit:=wdStory, Count:=1
                'insert a new line (paragraph)
                ReadTxtOrDocIntoDocument_1.Range.Paragraphs.Add
                'increase counter to read next txt line
                i = i + 1
            Loop
            '======================================================
            TxtFile.Close

            Set FSO = Nothing
            Set TxtFile = Nothing
        End Select

    Else

        MsgBox "no file path was provided"
        Exit Function
        'close the tempDoc after processing
    End If
End Function

1 Answer 1

4

The following was VBScript code. I made minimal changes so it will run in Excel 2010 as VBA code. You'll need to add a Reference to Microsft Scripting Runtime. You might want to bulk it up with proper type specifications, error-handling etc. It fails if the text file has less than 2 characters in it; you might want to handle that. The main problem with this encoding issue is that there is no encoding attribute in files. What we're doing here is using Byte-Order-Mark to identify encoding. A true test for encoding that doesn't depend on BOM will require for the file to be large and for us to do statistical analysis of contents to determine UTF-32/UTF-16/UTF-8/ANSI/ASCII/EBCDIC

    Public Function IsUnicodeFile(FilePath)
        Dim objFSO
        Dim objStream

        Dim intAsc1Chr
        Dim intAsc2Chr


        Set objFSO = CreateObject("Scripting.FileSystemObject")
        If (objFSO.FileExists(FilePath) = False) Then
            IsUnicodeFile = False
            Exit Function
        End If

        ' 1=Read-only, False==do not create if not exist, -1=Unicode 0=ASCII
        Set objStream = objFSO.OpenTextFile(FilePath, 1, False, 0)
        intAsc1Chr = Asc(objStream.Read(1))
        intAsc2Chr = Asc(objStream.Read(1))
        objStream.Close

        If (intAsc1Chr = 255) And (intAsc2Chr = 254) Then
            IsUnicodeFile = True
        Else
            IsUnicodeFile = False
        End If

        Set objStream = Nothing
        Set objFSO = Nothing
End Function
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.