gpt4 book ai didi

excel - 如何读取含有汉字的.txt文件?

转载 作者:行者123 更新时间:2023-12-03 02:31:06 26 4
gpt4 key购买 nike

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

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 按位置定位字符串效果非常好。然而,有时文件中包含中文字符,Input函数会向LstStr返回一个空字符串“”。我尝试使用其他一些建议的方法但徒劳(例如 Extract text from a text file with Chinese characters using vba )。我应该如何成功读取汉字文件,而不需要修改按位置提取数据的代码的其他部分?谢谢!

最佳答案

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

To use ADOBD you will need to add the reference Microsoft ActiveX Data Objects 6.1 Library (Version can be different) in VBA Menu › Extras › References

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

关于excel - 如何读取含有汉字的.txt文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43108884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com