我在文本文件中包含以下数据:
Member A
Diameter 60 in
Thickness 1 in
Yield Stress 50 ksi
Brace B
Diameter 54 in
Thickness 1 in
Yield Stress 50 ksi
当在长文本文件中找到一串文本“Member A”时,我需要提取数字直径(或厚度或屈服应力)。数据始终保持相同的顺序。
我可以使用“Trim”/“Mid”提取与我正在搜索的文本位于同一行的数据。我不知道如何参考我正在搜索的文字“下面一行”。
我的代码:
Sub jtdtlextract()
Dim str, str1, strOutPut, strBrcAngle, strComnJt, strChrdDia As String
Dim FileToOpen, FileConverted, strRun, lngReturn, fs, f, s, ff
FileToOpen = Application.GetOpenFilename("All Files (*.*), *.*")
If FileToOpen <> False Then
MsgBox FileToOpen, 0, "Open File"
End If
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(FileToOpen)
FileConverted = UCase(f.ParentFolder.Path) & "\jt_dtls_extracted.txt"
Open FileToOpen For Input Access Read Shared As #1
Open FileConverted For Output Access Write Shared As #2
Do Until EOF(1)
Line Input #1, str
str1 = LTrim(str)
If Left(str1, 31) = "Detailed Review Report of Joint" Then
strComnJt = Trim(Mid(str1, 35, 4))
strOutPut = "Common_Jt" & Space(1) & strComnJt
Print #2, strOutPut
End If
'I have a lot more information to extract from the text file
'I was hoping to use a method similar to above since it's
'fairly simple and I have no coding experience, the code
'above only works when the information needed is on the
'same line as the information searched for. Was written
'by someone else.
Loop
Close #1
Close #2
strRun = "Notepad.exe " & FileConverted
lngReturn = Shell(strRun)
End Sub
答案 0 :(得分:0)
您需要一些状态管理代码来跟踪您在文件中的位置。
如果文件不是太大,则不需要全流式传输,并且可以在数组中使用完整的缓冲。
然后你可以使用简单的索引自然地扫描这个数组:
name = lines(i)
diameter = parseDiameter(lines(i+1))
thickness = parseThickness(lines(i+2))
yieldStress = parseYieldStress(lines(i+3))
i = i + 5
答案 1 :(得分:0)
Do Until EOF(1)
Line Input #1, str
str1 = LTrim(str)
If Left(str1, 31) = "Detailed Review Report of Joint" Then
strComnJt = Trim(Mid(str1, 35, 4))
strOutPut = "Common_Jt" & Space(1) & strComnJt
Print #2, strOutPut
Line Input #1, strDiscardThisLine
Line Input #1, str3rdLine
strOutPut = Trim(Mid(str3rdLine,35,4))
Print #2, strOutPut
End If