作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个子例程,可以读取文本文件并从中提取某些数据。这是一个例子:
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/
我是一名优秀的程序员,十分优秀!