[英]EXCEL-VBA Return highest value from a find function from a txt file VBA
这是问题所在:
-我有一个包含大量数据的文本文件,但我必须提取包含字符串“ pressure:(values)”的行 。 该文件包含很多此字符串,我想在单词pressure之后提取最高值。 以下是文件中的一些示例内容:-压力:101.011-压力:20.1102-压力:20.1020
“压力:”的出现次数不是固定的。
我已经找到一些实现此目的所需的功能(只需复制并编辑一些在网上找到的脚本)。 但是我不知道如何存储匹配的值(也许存储在数组中?)然后应用max函数返回最大值。 将不胜感激任何输入。
也欢迎实现期望任务的其他方法。
这是我的脚本:
Sub search()
Const ForReading = 1
Dim FSO, FileIn, strTmp
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FileIn = FSO.OpenTextFile("D:\data.txt", ForReading)
Do Until FileIn.AtEndOfStream
strTmp = FileIn.ReadLine
If Len(strTmp) > 0 Then 'read if not blank
If InStr(1, strTmp, "pressure:", vbTextCompare) > 0 Then 'find function
x = Mid(strTmp, 10, 7) 'to extract the numeric values only
MsgBox x 'just for checking if value of x is correct
'add function that will return the highest value
'WorksheetFunction.Max (x)
End If
End If
Loop
FileIn.Close
End Sub
如果您只想要单个最大压力值,则只需跟踪到目前为止找到的最大值,并在找到更大的值时对其进行更新。
这是您的代码重构,并解决了其他一些小问题(标记为<---
更改)
Sub search()
Const ForReading = 1
'<--- Use specific data types rather than variant
Dim FSO As Object
Dim FileIn As Object
Dim strTmp As String
Dim KeyWord As String
Dim i As Long, j As Long
Dim x As Double
Dim MaxX As Double
MaxX = -4.94065645841247E-324 '<-- initialise to lowest possible value
KeyWord = "pressure:" ' <--- generalise the function
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FileIn = FSO.OpenTextFile("D:\data.txt", ForReading)
Do Until FileIn.AtEndOfStream
strTmp = FileIn.ReadLine
If Len(strTmp) > 0 Then 'read if not blank
i = InStr(1, strTmp, KeyWord, vbTextCompare)
If i Then 'find function
' <-- cope with possibility Pressure is not at start of string
' and may have trailing data
strTmp = Trim$(Mid$(strTmp, i + Len(KeyWord)))
i = InStr(strTmp, " ")
If i Then
strTmp = Trim$(Left$(strTmp, i - 1))
End If
x = Val(strTmp) 'to extract the numeric values only
MsgBox x 'just for checking if value of x is correct
'add function that will return the highest value
If x > MaxX Then MaxX = x
End If
End If
Loop
FileIn.Close
MsgBox "Max presseure is " & MaxX
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.