从文本文件中读取关键文本,直到下一个换行符

时间:2015-09-15 07:48:17

标签: excel vba excel-vba

我有一个像这样的文本文件:

----------------DELEGATE TIME & RESOURCE STATS-----------------
A Type: Supplier Registration
A Component: Bid preparation (K/O, overview doc, review, decision)
A Completed By: Mark O'Brien
A Hours: 1
-------------------------END OF STATS--------------------------

然后我的Excel VBA代码扫描我的记事本文件并获取冒号后面的值:

A Type: {Get Value}
A Component: {Get Value}
A Completed By: {Get Value}
A Hours: {Get Value}

我的代码:

Dim myFile As String, text As String, textline As String, posLat As Integer, posLong As Integer
myFile = "\\MI-FILESERVE1\Shared Folders\Shared_Business_Dev\Tenders\" & Range("G" & ActiveCell.Row).Value & "\" & Range("E" & ActiveCell.Row).Value & "\" & Range("F" & ActiveCell.Row).Value & " - " & M & " - " & Y & "\log.txt"

Open myFile For Input As #1

Do Until EOF(1)
    Line Input #1, textline
     text = text & textline
Loop
Close #1


A = InStr(text, "A Type")
1= Mid(text, A + 8, 50)

使用此部分代码,通过查找“A Type”一词,然后从值中修剪“A Type”,为我提供以下“供应商注册”值。

使用此行的问题:

1= Mid(text, A + 8, 50)

我必须定义该值的长度是多少,实际上每个值每次都是不同的字符长度,所以不是使用字符数,我可以做一些像完成'A Type:'之后的字符长度,直到下一个换行符,这样我就不会得到:

Supplier RegistrationA Component:......

有人可以告诉我该怎么做吗?

3 个答案:

答案 0 :(得分:0)

有很多方法。最快的可能是Split

dim result as variant
Line Input #1, textline
result = Split(texteline, ": ")
debug.print result(0) & ": " & result(1)

答案 1 :(得分:0)

另一个选项是Mid

Mid(Text, InStr(Text, ":") + 2, Len(Text))

InStr找到起始位置,+ 2从第一个字符开始,Len(Text)设置String的长度。

<强>更新

使用您的特定代码,它将如下所示:

Dim myFile As String, text As String, textline As String, posLat As Integer, posLong As Integer
myFile = "\\MI-FILESERVE1\Shared Folders\Shared_Business_Dev\Tenders\" & Range("G" & ActiveCell.Row).Value & "\" & Range("E" & ActiveCell.Row).Value & "\" & Range("F" & ActiveCell.Row).Value & " - " & M & " - " & Y & "\log.txt"


Open myFile For Input As #1

Do Until EOF(1)
    Line Input #1, textline
    If Left(textline, 1) <> "-" Then
        text = Mid(textline, InStr(textline, ":") + 2, Len(textline))
        'proces text code here
    End If
Loop
Close #1
End Sub

答案 2 :(得分:0)

声明更多变量并使用下面的代码替换do循环

' Declare necessary variable
Dim aType As String
Dim aComponent As String
Dim aCompleted As String
Dim aHours As String
Dim i As Long


' Replace this do loop to your do loop code
Do Until EOF(1)
    Line Input #1, textline
    i = InStr(textline, "A Type:")
    If InStr(textline, "A Type:") > 0 Then
        aType = Mid(textline, A + 8, Len(textline))
    End If

    i = InStr(textline, "A Component:")
    If InStr(textline, "A Component:") > 0 Then
        aType = Mid(textline, A + 13, Len(textline))
    End If

    i = InStr(textline, "A Completed By:")
    If InStr(textline, "A Completed By:") > 0 Then
        aType = Mid(textline, A + 16, Len(textline))
    End If

    i = InStr(textline, "A Hours:")
    If InStr(textline, "A Hours:") > 0 Then
        aType = Mid(textline, A + 9, Len(textline))
    End If
Loop