从txt文件中提取string

背景

我必须在Excel VBA中创build一个代码,该代码打开一个文本文件,并将以“:60F”开头的一些string的特定部分写入到Excel工作表的特定单元格中。

这部分代码已经工作。

问题

但是,我正在为第二部分的任务而挣扎。 我必须写入Excel文档的另一个单元格中以“:61:”开头的特定string的一部分。

问题是,以“61:”开始的文本文件中有很多string,但是我需要在以“60F:”开头的string之后出现的string。

如果你能帮助我,我将非常感激。 提前非常感谢!

亲切的问候

这是我迄今写的代码:

Function extract_opening_balance(ByVal filename As String, subfield_61 As String) As String Dim i As Integer Dim pos1 As Integer strPath = ActiveWorkbook.Path & "\Data of Reporting Month\" filename = strPath & "MT940_T2_" & main_menu.cbo_Year & Left(main_menu.cbo_Month, 2) & Format(day(CDate(Right(main_menu.lst_Date.List(i), 10))), "00") & ".txt" Open filename For Input As #1 For i = 3 To 13 Do Until EOF(1) Line Input #1, textline If InStr(textline, ":60F:") > 0 Then If InStr(textline, "EUR") = 13 And InStr(textline, 0) <> 16 Then 'For j = 1 To String(":60F:").Count pos1 = InStr(subfield_61, "//") + 30 'time_str = Mid(subfield_61, pos1, 6) 'time_str = Mid(time_str, 1, 2) & ":" & Mid(time_str, 3, 2) & ":" & Mid(time_str, 5, 2) Sheets("op_balance").Range("B" & i).Value = Mid(textline, 6, 1) Sheets("op_balance").Range("C" & i).Value = Mid(textline, 16, 20) Sheets("op_balance").Range("D" & i).Value = subfield_61 Sheets("op_balance").Range("E" & i).FormulaR1C1 = "=IF(RC[-3]=""D"",(-1)*RC[-2],RC[-2])" 'Next j End If End If Loop Next i End Function 

一个正则Regexp选项:

随机的东西
随机的家伙
东西:60F:东西
其他东西61:getme
60F更多

61之后返回字母数字(前面是:60F :) ,即在这个例子中是getme

 Sub GetMe() Dim FSO As Object Dim FH As Object Dim objRegex As Object Dim objRegexMC As Object Dim strIn As String Set FSO = CreateObject("Scripting.FileSystemObject") Set FH = FSO.OpenTextFile("c:\temp\test.txt") Set objRegex = CreateObject("vbscript.regexp") strIn = FH.readall strIn = Replace(strIn, vbNewLine, Chr(32)) With objRegex .Pattern = ":60F.*61:(\w+)" If .Test(strIn) Then Set objRegexMC = .Execute(strIn) MsgBox objRegexMC(0).submatches(0) Else MsgBox "text not found" End If End With End Sub