【问题标题】:Import Unicode characters from txt file to MS-Word with VBA使用 VBA 将 Unicode 字符从 txt 文件导入 MS-Word
【发布时间】:2017-11-26 06:48:35
【问题描述】:

我正在使用此代码将 txt 文件中的一行导入 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

但是,文本文件是用越南语编写的,因此其中有大量的 unicode 字符。当数据被插入到 Word 中时,它被严重搞砸了(例如,“thời gian”变成了“ÿþthÝ i gian”)。

我尝试使用 Unicode 编码保存文本文件,但它不起作用。

有什么办法可以解决这个问题吗?

【问题讨论】:

  • 什么是txt文件编码,Unicode还是UTF-8?您应该使用Scripting.FileSystemObjectADODB.Stream 来读取具有该编码的文件。
  • 谢谢,去试试。

标签: vba unicode ms-word


【解决方案1】:

以下代码似乎保留了格式。您需要设置对“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

【讨论】:

    猜你喜欢
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    相关资源
    最近更新 更多