line input problem-need to return 5 lines after a string is found

F

festdaddy

I've been tinkering with this for a few hours and can't seem to get it
to work correctly.
I'm using line input to go through each line looking for a string. When
the string is found, i want to return the line it came from, and the 4
lines below it. Would this be easier with an array? Or do I just have
the loop/for sequencing wrong?

sub return5lines ()

dim filename as sstring = "C:\myfile.txt"
dim strdata as string
dim texttofind as string = "my text"

Open filename For Input As #1
Do Until EOF(1)
Line Input #1, strdata
If InStr(1, strdata, texttofind) Then
i = 1
End If
For i = 1 To 5
ActiveSheet.Range("a" & i) = strdata
i = i + 1
Loop
Close #1

end sub
 
T

Tom Ogilvy

sub return5lines ()

dim filename as sstring = "C:\myfile.txt"
dim strdata as string
dim texttofind as string = "my text"

Open filename For Input As #1
Do Until EOF(1)
Line Input #1, strdata
If InStr(1, strdata, texttofind) Then
For i = 1 To 5
ActiveSheet.Range("a" & i) = strdata
Line Input #1, strDate
next
exit do
end if
Loop
Close #1

end sub
 
L

Laurin

try this


Code
-------------------
sub return5lines ()

dim filename as sstring = "C:\myfile.txt"
dim texttofind as string = "my text"
dim output() as string, count as long, I as integer
I = 6
Open filename For Input As #1
Do Until EOF(1)
Line Input #1, strdata
If InStr(1, strdata, texttofind) or I < 5 Then
count = count + 1
Redim Preserve output(count)
output(count)=strdata
If InStr(1, strdata, texttofind) then
I = 1
Else
I = I + 1
End If

Loop

Close #1

Range("A1").select
Range(Selection, Selection.Offset(count, 0)).Select
Selection.Name = "OutputData"
[OutputData]=Application.Worksheetfunction.transpose(output)

end su
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top