gpt4 book ai didi

VBA 读取/搜索文本文件

转载 作者:行者123 更新时间:2023-12-04 20:46:29 27 4
gpt4 key购买 nike

我正在尝试读取一个有 1147 行的文本文件。下面的代码仅读取第 1050-1147 行。我的目标是读取整个文件并提取位于不同行的特定值以在脚本中使用。一个示例是包含“BlockList: 2”的行中的值 2。我已经包含了文本文件格式的片段,因为它的格式不同于我遇到的任何示例(第 1116-1128 行);我试图访问的值的缩进与显示的第一行相同(不确定这是否重要)。

    fixation.OffsetTime: 426611
*** LogFrame End ***
Level: 2
*** LogFrame Start ***
Procedure: TestProc
BlockList: 2
BlockList.Cycle: 1
BlockList.Sample: 2
Running: BlockList
*** LogFrame End ***

1级
* LogFrame 开始 *
实验:ChoiceofLotteries_fMRI_I

到目前为止的代码:
Sub OpenTextFileTest()
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Dim fs, f, contents, var1
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile("C:\NameOfFile.txt", 1)
contents = f.ReadAll
f.Close
Debug.Print contents
End Sub

有没有人有任何建议如何做到这一点?

最佳答案

试试这个(关于如何提取 BlockList: 值的示例)

Sub Sample()
Dim MyData As String, strData() As String
Dim i As Long

'~~> Replace this with the relevant file
Open "C:\NameOfFile.txt" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)

For i = LBound(strData) To UBound(strData)
If InStr(1, strData(i), "BlockList:", vbTextCompare) Then
Debug.Print Split(strData(i), ":")(1)
Exit For
End If
Next i
End Sub

跟进

您拥有的文本文件是 Unicode文本文件,因此您遇到了这个问题。如果你做 SaveAs然后选择 ANSI在编码中然后运行上面的代码,是否有效?

点击 here对于 reading txt files using VBA 的另一种方式

关于VBA 读取/搜索文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14387015/

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