excel - 搜索字符串并返回行号 VBA
问题描述
我对 VBA Excel 编程很陌生。我有一个文本文件,其中某些点的 x、y、z 坐标。它在开始时也有一些不需要的信息。我所需的信息仅出现在字符串“1-xxx”之后的第 20 行。我的代码是打开这个文件,逐行遍历,搜索字符串'1-xxx'并返回行号。然后将此行号输出作为输入提供给下方“.TextFileStartRow”字段中记录的宏。我在互联网上搜索并写了这样的东西。但问题是我只得到搜索文本的字符位置,而不是我预期的行号。我哪里错了?
Sub Macro()
Dim Pos_rw As Integer, text As String, textline As String
Dim folder As String, StartingDir As String
Dim file
StartingDir = ThisWorkbook.Path
ChDir StartingDir
file = Application.GetOpenFilename("Text Files (*.txt), *.txt")
Open file For Input As #1
Do Until EOF(1)
Line Input #1, textline
text = text & textline
Loop
Close #1
Pos_rw = InStr(text, "1-xxx")
With ActiveSheet.QueryTables _
.Add(Connection:="TEXT;" & file, Destination:=Range("$D$2:$F$26"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1252
.TextFileStartRow = Pos_rw
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = ":"
.TextFileColumnDataTypes = Array(9, 9, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
解决方案
解决方案是跟踪循环中的行号,一旦您找到您正在寻找的行,它就会终止:
Sub Macro()
Dim Pos_rw As Long
Dim textline As String
Dim folder As String, StartingDir As String
Dim found As Boolean
Dim file
StartingDir = ThisWorkbook.Path
ChDir StartingDir
file = Application.GetOpenFilename("Text Files (*.txt), *.txt")
Open file For Input As #1
Do Until EOF(1) or found
Pos_rw = Pos_rw + 1
Line Input #1, textline
If InStr(textline, "1-xxx") > 0 Then found = True
Loop
Close #1
'the rest of your logic, including some safety code if found = False here
End Sub
一个小点:我改成Dim Pos_rw As Integer
了Dim Pos_rw As Long
. 在现代 VBA中使用几乎没有充分的理由Integer
(除非您以某种方式或其他方式在 16 位处理器上运行它)。您无缘无故地冒着溢出的风险。
推荐阅读
- git - 如何:推入 repo A,从 repo B 拉取,然后从 A 推到 B
- laravel - Laravel Mix webpack 块文件从错误的路径加载
- ios - 我们如何在 React Native Slider 中更改默认背景?
- c++ - yum : 在 centos 上使用 boost 1.69 而不是默认 (1.53) 版本
- flutter - Flutter BLoC 测试
- javascript - 如何使用这个简单的 Plotly?
- ios - 无法访问字典中的值
- windows - 复制带有空格和大引号的文件
- kubernetes - 为什么有些 Kubernetes 的资源创建后是不可变的?
- python - SessionNotCreatedException:消息:会话未创建:此版本的 ChromeDriver 仅支持 Chrome 版本 81 I