使用VBA,数据和变量在不同的行上解析.txt文件中的数据

时间:2015-09-15 22:49:06

标签: excel vba parsing text

我有一个.txt文件,用于更改某些变量显示的格式

我可以使用以下代码成功提取时间数据:

档案数据:

+---------------------+------------------------------------------------------------------+
| Start Time      | 09/06/2015 02:28:58                                              |
| Finish Time     | 09/06/2015 03:12:33                                              |
+---------------------+------------------------------------------------------------------+

代码:

'open .txt files from defined folder(s)
  Set fso = CreateObject("Scripting.FileSystemObject")
  For Each f In fso.GetFolder("C:\Localdata\XYZ").Files
    If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
      'define Row
      Row = Row + 1
      'open each file as a text stream and read until end of file
      Set stream = f.OpenAsTextStream
      Do While Not stream.AtEndOfStream
        Line = stream.ReadLine
        'extract the data associated with the text for items in data line
        If InStr(1, Line, "Start Time") Then
        'Add each value to the next available row in designated column (A,B...)
           Range("A60000").End(xlUp).Offset(1, 0).Value = Trim(Split(Line, "|")(2))
        End If

但是,现在我尝试以这种方式出现在文件中的解析数据:

|                                 |                   Variable                 |
|                                 +-----------+-----------+--------+-----------+
|            Object               |  Value1   |  Value2   | Value3 |  Value4   |
|                                 |           |           |        |           |
+=================================+===========+===========+========+===========+
| Type                            |     5.00 |     10.00  |   15.00|     20.00 |
+---------------------------------+-----------+-----------+--------+-----------+

我想标记文字"变量"并在Value2(10.00)下拉取值。 我有几张桌子"像这样在具有可变间距和字符长度的文本文件中

如何让它从感兴趣的文本字符串中跳过几行?

1 个答案:

答案 0 :(得分:1)

我有朋友帮我解决这个问题,我们发现提取我想要的确切数据的唯一方法是关闭唯一文本,然后关闭定义表格的+ ---字符:

If InStr(1, LineTxt, "Variable", vbTextCompare) Then ' Look For unique text in desired table - this starts the next search for "Object"

    a = 0 'Use this as a switch for breaking out of next DO LOOP

Do While a <> 1 'Do this unti a = 1

    Line Input #1, LineTxt ' Read line from

    If InStr(1, LineTxt, "+==========") Then ' Look for Type - This only occurs after "Object" is found, so it will not happen other time "Type" occurs in the log.
    Line Input #1, LineTxt ' read a line on each loop
    Row = Row + 1 ' Increment counter for row
       Worksheets("Output").Range("J60000").End(xlUp).Offset(1, 0).Value = Trim(Split(LineTxt, "|")(3)) 'Once "Type" is found, split the line and write the data to a cell on worksheet "Output"

    a = 1 ' Set swith to 1 - The Do / While loop will break due to this switch change.
    End If
Loop ' Loop until a = 1

结束如果

感谢所有提供建议的人。我在这个论坛上学到了很多东西!