Hi,

I have this problem which I do not know how to solve in VB.
I have to read from a text file, but only write selective lines to a new txt file.

E.g. (original text file)

============================================

 SINNWSQ
.SINFMSQ 230606
SSM
LT
23MAR00323C108
NEW
SQ 3328
01NOV04 31DEC20 2
J TRK
DFW1700/0 BNA1100/1
SI GSQ TRK DFW-BNA
230615 MAR10 SCZ 186
@NNNN

SINNWSQ
.SINFMSQ 230606
SSM
LT
23MAR00323C109
NEW
[COLOR="Red"]SQ 3840
29NOV04 31DEC20 1234567
J TRK
EWR2100/0 BNA0430/1
SI GSQ TRUCK EWRBNA - ACI
230615 MAR10 SCZ 187[/COLOR]
@NNNN

============================================

I need to write to a new file only those lines after NEW and finish writing when line is @NNNN. (i.e. those text in red)

My code is below.

Can anyone help me on this? Appreciate your help!!! Thank you.

Public Function readExtFile1(filename As String) As String 
    nFileNum = FreeFile
    Open App.Path & "\" & filename For Input As nFileNum

    Do While Not EOF(nFileNum)
        Line Input #nFileNum, sNextLine
        sText = sText & sNextLine & vbCrLf
        If text = "NEW" Then
            WriteToTextFile (sNextLine)
        End If
    Loop
    Close nFileNum
End Function

Public Function WriteToTextFile(text As String) As String
    'set and open file for output
    MyFile = "E:\Work\readTextFile\" & "written.txt"
    fnum = FreeFile()
    Open MyFile For Output As fnum
    Print #fnum, text 'print will remove the qutotation mark
    Close #fnum
End Function

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Close, very close, but add a boolean variable... (Also, since you are not returning anything from this procedure, it can be a sub instead of a function...)

Public Sub readExtFile1(filename As String)
Dim TimeToWrite As Boolean

Then, there are a couple of mistakes in your code we need to correct...

Line Input #nFileNum, sNextLine
[B]sText = sText & sNextLine & vbCrLf[/B]
If [B]text[/B] = "NEW" Then
WriteToTextFile (sNextLine)
End If
Loop
Close nFileNum 'missing something here see below

It should be...

Line Input #nFileNum, sNextLine
  If UCase(sNextLine) = "NEW" Then TimeToWrite = True
  If UCase(sNextLine) = "@NNNN" Then TimeToWrite = False
  If TimeToWrite = True And UCase(sNextLine) <> "NEW" Then WriteToTextFile (sNextLine)

Loop
Close [B]#[/B]nFileNum

Good Luck

Wow! Thanks! That solved my problem, you are really good!

Appreciate your pointer.

This question has already been answered. Start a new discussion instead.