VBA - 从.txt文件中识别和复制行

时间:2016-10-15 00:46:55

标签: vba excel-vba excel

我正在使用以下代码逐行浏览txt文件和(1)识别文本字符串和(2)导入以下50位数字。我想找到一种从txt文件导入整个ROW的方法,但我不确定代码。另外,有没有办法告诉VBA在txt文件中找到SECOND或THIRD字符串?目前,下面的代码只是定位第一次出现。谢谢!!

Sub CopyTXT()

myFile = "G:\Filings\Test\Test.txt"
Open myFile For Input As #1

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

Close #1

Revenue = InStr(Text, "Operating Revenues")

 'This is where I'm confused - not sure how to copy that row, so I simply pick a large value and use a mid formula - would like to change this.
Range("H1").Value = Mid(Text, Revenue + 7, 50)

End Sub

1 个答案:

答案 0 :(得分:2)

这样的事情(假设您要查找的文字在一行而不是分割成行)

Sub CopyTXT()

    Dim myFile, textline
    Dim i As Long

    i = 0
    myFile = "G:\Filings\Test\Test.txt"

    Open myFile For Input As #1

    Do Until EOF(1)
        Line Input #1, textline

        If InStr(textline, "Operating Revenues") > 0 Then
            i = i + 1

            If i = 2 Then
                Range("H1").Value = textline
            End If

        End If

    Loop

    Close #1

End Sub