1 Replies - 288 Views - Last Post: 01 November 2017 - 07:45 AM Rate Topic: -----

#1 Alex27  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 29-October 17

Copy previous word from a specific string in a text file and paste

Posted 29 October 2017 - 11:08 PM

Hi.
I have a text file, its look like...

word 1

Line

word 2

Line

word 3

Line

I have a code that find all the strings "Line" in a text file, and copy the previous line (word 1, word 2, word 3) before "Line" and paste them into Excel cells.

Option Explicit

Sub GetText()
    Dim fName As String
    Dim Word1 As String, Word2 As String, i As Long
    
    fName = "C:\Test\FindLine.txt"
    
    Open fName For Input As #1
    
    Do Until EOF(1)
        Word1 = Word2
        Input #1, Word2
        If Word2 = "Line" Then
            i = i + 1
            Cells(i, 1) = Word1
        End If
    Loop
    
    Close #1
End Sub


But how i copy previous lines, if text file loks like...

word 1

Line/123

word 2

Line/456

word 3

Line/789


Please suggest.

Is This A Good Question/Topic? 0
  • +

Replies To: Copy previous word from a specific string in a text file and paste

#2 t3cho  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 223
  • Joined: 27-May 14

Re: Copy previous word from a specific string in a text file and paste

Posted 01 November 2017 - 07:45 AM

If you are sure that you will allways have Line as prefix

Word2 = Word2.SubString(0, 4)

This post has been edited by t3cho: 01 November 2017 - 07:45 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1