简体   繁体   中英

Import Unicode characters from txt file to MS-Word with VBA

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM