从txt文件到excel的特殊字符

时间:2017-09-29 14:03:41

标签: excel excel-vba special-characters vba

我正在尝试将特殊字符从txt文件导入excel。 我已经尝试了很多东西,但角色BREAK在excel中。 我的字符串示例:

in txt:Changjíhuízúzìzhìzhou 擅长转换为:ChangjÃhuzúzïzïzhou

所以我试着一点一点地移动值,但没有运气..

Sub ImportTXTFile()

Dim file As Variant
Dim EXT As String
Dim Direct As String    ' directory...
Direct = "C:\FilePath\Here\"
EXT = ".txt"
Dim COL As Long
Dim row As Long
COL = 1
row = 1

file = Dir(Direct)

Do While (file <> "")   ' Cycle through files until no more files
    If InStr(file, "Data.txt") > 0 Then 
        '
        Open Direct & "Data.txt" For Input As #1               
        '
        While Not EOF(1)
            Line Input #1, DataLine ' Read in line
            Do While DataLine <> ""
                If InStr(DataLine, ",") = 0 Then    ' Drop value into excel upto the first ,
                    Sheets("test").Cells(row, COL).Value = DataLine
                    DataLine = ""
                Else
                    Sheets("test").Cells(row, COL).Value = Left(DataLine, InStr(DataLine, ",") - 1)
                    DataLine = Right(DataLine, Len(DataLine) - InStr(DataLine, ","))    ' rebuild array without data upto first ,
                End If
                COL = COL + 1   ' next column
            Loop
            COL = 1             ' reset column
            row = row + 1       ' write to next row
        Wend
        '
        Close #1    ' Close files straight away
    End If
    file = Dir
Loop
MsgBox "Data Updated"
End Sub

2 个答案:

答案 0 :(得分:1)

使用first link我给你的,这是一个测试代码,我测试成功。使用charsetCdoISO_8859_1

Dim objStream As Object
Dim strData As String
Set objStream = CreateObject("ADODB.Stream")
objStream.Charset = "iso-8859-1"
objStream.Open
objStream.LoadFromFile ("C:\Users\user_name\Desktop\test.txt")
strData = objStream.ReadText()
Debug.Print strData & " Compare to: Changjíhuízúzìzhìzhou"

输出为:immediate

编辑:

检查.txt文件的编码类型并导入到具有相同编码字符集的Excel,例如,我将test.txt更改为UTF-8并使用.Charset成功导入为"utf-8"

您可以另存为.txt文件并选择编码。

.txt save as

答案 1 :(得分:1)

所以我想哭,因为所有这些UTF-8到ASCII的转换都可以简单地通过以下方式避免: 在Notepad ++中打开txt文件 转到编码选项卡 点击转换为ASCII

运行我的原始代码。 BLAM 一切都很完美。

感谢danieltakeshi的所有帮助!