[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 171
  • Last Modified:

Check if a string exists in a text file.

I have to perform an action in VBA for Word depending on whether a given phrase appears in a text file.

How can I make an IF THEN statement depend on whether or not the string appears in the document?

Thanks.

       Leprechaun
0
Leprechaun
Asked:
Leprechaun
1 Solution
 
mark2150Commented:
IF INSTR(LongTextString, "What I'm Seaching for") > 0 THEN ...

Now you should use UCASE on both those clauses to make it more robust. If you need help realding the contents of the text file into LongTextString let me know.

M
0
 
tureCommented:
Leprechaun,

Here is some Word VBA code that checks if the active document contains the text "Corned Beef".

Private Sub Command1_Click()
  Dim doc As Word.Document
  Dim f As Boolean
  Dim rng As Word.Range
     
  Set doc = AvtiveDocument
  Set rng = doc.Range(0, 0)
   
  With rng.Find
    .Text = "Corned Beef"
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchWildcards = True
  End With
   
  f = rng.Find.Execute
  If f = True Then
    Msgbox "Found it!"
  Else
    Msgbox "No beef..."
  End
End Sub

Ture Magnusson
Karlstad, Sweden
0
 
LeprechaunAuthor Commented:
Thanks for your response, Mark.

Yeah, I do need help "reading the contents of the text file into LongTextString".

Thanks in advance...

Leprechaun
0
 
eab111098Commented:
public function TheStringIsInTheFile(byval Str as string,byval FName as string) as boolean
dim FN as integer
dim LNStr as string
dim Found as boolean
rtnval = false
Found = false
fn = freefile
open fname for input as fn
if not eof(fn) then
  do
    line input#fn, LNStr
    if instr(1,LNStr,Str) <> 0 then Found = true
  loop until Found or eof(fn)
end if
close fn
TheStringIsInTheFile = Found
end function


this routine will find a string in a "TEXT" file.

to call it

if TheStringIsInTheFile("string to search for", "drive:\directory\filename") then

branch to where you want......

end if

is this what you were looking for?

ed.
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now