Click to See Complete Forum and Search --> : Challanges here! Get your Challenges here! Free Challenges!


BrewGuru99
October 21st, 1999, 12:31 PM
Okay, I have a text file that I'm doing a InStr search through for a word. When I find that word, I want to return the line that the word is on.
Example:


Dim Str1 as string, Pointer as Long
'set string (this is basically what it will be like.)
Str1 = _
"Blah blah blah" & vbcrlf & _
"Hooo Haa Hee ha" & vbcrlf & _
"My search will find a word in this line." & vbcrlf & _
"more text........" & vbcrlf

'Find the word
Pointer = InStr(Str1, "in")
If Pointer > 0 then
....
'Return the "line" of text. In this instance, it would return:
'"My search will find a word in this line."
....




I don't need the vbcrlf, but i can filter that out after the fact.

Brewguru99

Aaron Young
October 21st, 1999, 01:09 PM
Try this:

private Sub Command1_Click()
Dim sString as string
Dim sFound as string

'set string (this is basically what it will be like.)
sString = "Blah blah blah" & vbCrLf & _
"Hooo Haa Hee ha" & vbCrLf & _
"My search will find a word in this line." & vbCrLf & _
"more text........" & vbCrLf

sFound = GetLine(sString, "in")
If len(sFound) then
MsgBox sFound
else
MsgBox "Not Found"
End If

End Sub

Function GetLine(byval sString as string, byval sFind as string) as string
Dim lPointer as Long
Dim lLine as Long
Dim sLine as string

'Find the word
lPointer = InStr(sString, sFind)
If lPointer then
lLine = InStrRev(sString, vbCrLf, lPointer)
sLine = mid(sString, IIf(lLine, lLine, 1))
If Left(sLine, 2) = vbCrLf then sLine = mid(sLine, 3)
GetLine = mid(sLine, 1, InStr(sLine, vbCrLf) - 1)
End If

End Function

'If you have an earlier version of VB, (Prior to Vb6),
'Change the Occurance of InStrRev in the GetLine Function to InStrRev2
private Function InStrRev2(byval sString as string, byval sChars as string, optional byval lPos as Long = 1) as Long
'Duplicate Functionality of the VB6 Function InStrRev
If len(sString) = 0 then Exit Function
If lPos = 1 then lPos = len(sString)
While mid(sString, lPos, len(sChars)) <> sChars And lPos > 1
lPos = lPos - 1
Wend
If lPos = 1 And Left(sString, len(sChars)) <> sChars then
InStrRev2 = 0
else
InStrRev2 = lPos
End If
End Function




Usage: sTheLine = GetLine(sSearchText, sFindInText)

Aaron Young
Analyst Programmer
adyoung@win.bright.net
aarony@redwingsoftware.com

BrewGuru99
October 21st, 1999, 02:02 PM
Nice work man! I should really invest in vb6, this past hour I wasted would have actually been productive.

Brewguru99