2
votes

I'm using this code to import a line from a txt file into word:

Sub QuickType8()
    Dim strFilename As String
    Dim strTextLine As String
    Dim iFile As Integer: iFile = FreeFile
    Dim iLine As Integer
    On Error GoTo lbl_Exit
    strFilename = "C:\Users\Long\Dropbox\WIP word documents\5) Common Phrases.txt"

    Open strFilename For Input As #iFile
    iLine = 0
    Do Until EOF(1)
        iLine = iLine + 1
        Line Input #1, strTextLine
        If iLine = 8 Then
            Exit Do
        End If
    Loop
    Close #iFile
    Selection.Text = strTextLine
lbl_Exit:
    Exit Sub
End Sub

However, the text file is written in Vietnamese, so there're tons of unicode characters in it. When the data got inserted into Word, it's messed up badly (eg. "thời gian" became "ÿþthÝ i gian").

I tried saving the text file using Unicode encoding, but it doesn't work.

Is there any way I can get around this issue?

1
What is txt file encoding, Unicode or UTF-8? You should use Scripting.FileSystemObject or ADODB.Stream to read a file with that encodings.omegastripes
Thanks, gonna try it.nguyen long

1 Answers

0
votes

Following code seems to retain the formatting. You need to set reference to "Microsoft Scripting Runtime".

Sub QuickType8()
Dim fso As New FileSystemObject
With fso
    Set strm = .OpenTextFile("C:\PERSONAL\Temp\abc.txt", ForReading, False, TristateTrue)
    stex = Split(strm.ReadAll(), vbCrLf)
    For i = LBound(stex) To UBound(stex)
        If i = 8 Then Exit For
        strtx = strtx & vbCrLf & stex(i)
    Next
    Selection.Text = strtx
End With
End Sub