如何读取带有中文字符的.txt文件?

时间:2017-03-30 04:58:46

标签: excel-vba vba excel

我有一个子程序,它读取文本文件并从中提取某些数据。这是一个例子:

NamePrefix = "Example"
OutputPath = "C:\Example"
DbSize = 65536

LstStr = ""
Dim Success() As Boolean
Dim Value() As Double
ReDim Success(1 to DbSize)
ReDim Value(1 to DbSize)
For ID = 1 to DbSize
  'Read string
    FileName = NamePrefix & Format(ID,"000000") & ".lst"
    FilePath = OutputPath & "\" & FileName
    Open FilePath For Input As 1
    LstStr = Input(LOF(1),1)
    Close 1
  'Extract data
    If InStr(1, LstStr, "SUCCESS") <> 0 Then Success(i) = True Else Success(i) = False
    Pos1 = InStr(1, LstStr, "TH 1 value: ") 'Position varies for each file
    Value(i) = Val(Mid(LstStr, Pos1 + 13, 10)) 'Value in scientific notation
Next ID

当只有字母,数字和符号时,使用 InStr 按位置定位字符串可以很好地工作。但是,有时文件包含中文字符,输入函数返回空字符串“”到 LstStr 。我尝试使用其他一些建议的方法,但徒劳无功(例如Extract text from a text file with Chinese characters using vba)。如何成功读取带有中文字符的文件,我不需要修改按位置提取数据的代码的其他部分?谢谢!

1 个答案:

答案 0 :(得分:3)

这是读取字符串的另一种方法。确保.Charset设置为您要阅读的文件的字符集。

  

要使用ADOBD,您需要在VBA菜单>附加功能>参考中添加引用 Microsoft ActiveX Data Objects 6.1库(版本可以不同)

Dim adoStream As ADODB.Stream
Set adoStream = New ADODB.Stream

adoStream.Charset = "UTF-8" 'set the correct charset
adoStream.Open
adoStream.LoadFromFile FilePath

LstStr = adoStream.ReadText

adoStream.Close
Set adoStream = Nothing
相关问题