问题在于:
- 我有一个包含大量数据的文本文件,但我必须提取包含字符串“pressure:(values)”的行。该文件有很多这个字符串,我想在压力之后提取最高值。以下是文件中的一些示例内容: - 压力:10.1101 - 压力: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
答案 0 :(得分:0)
如果您只需要单个最大压力值,那么只需跟踪到目前为止找到的最大值,如果找到更大的值,则更新它。
这是您的代码重构,其中包含一些其他小问题(标记为<---
的更改)
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