none
Using Find.Execute to Search for a Text in a word Document Problem RRS feed

  • Question

  • Hello: 

    I have a problem while searching for a text in a document, I search for multiple keywords in a document and the problem is that the code runs for only one time for the first word only. I've tried many alternatives instead of giving Find.Execute a single object I thought about an array it didn't work. I've tried to invoke the searching function many times with different words it only works for the first word only. 

    I want to point that the function runs normally but the if statement where I search doesn't work more than once. 

    here is the sample of the code.

     object missing = System.Type.Missing;
                //// search all in one 
                object[] words = { "references", "contents","abstract"};
                int foundpages =0;
                wordApp.Selection.Find.ClearFormatting();
                for (int i = 0; i < words.Length; i++ )
                {
                    for (int j = 0; j < TotalNumPages; j++)
                    {
                        //Console.WriteLine(words[i]);
                        if (wordApp.Selection.Find.Execute(words[i],
                        false, ref missing, ref missing, ref missing, true, ref missing,
                        ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref missing))
                        {
                            foundpages = wordApp.Selection.Range.get_Information(Word.WdInformation.wdActiveEndPageNumber);
                            Console.WriteLine("found word " + words[i] + " at page: " + foundpages);
                        }
                    }
                }

    Can anyone suggest a solution for this problem as I need to run this part of code too many times to do it manually. 

    Thanks.

    Friday, August 7, 2015 4:30 PM

Answers

  • Try something based on the following VBA code:

    Sub Demo()
    Application.ScreenUpdating = False
    Dim ArrFnd, i As Long, StrPgs As String
    ArrFnd = Array("references", "contents", "abstract")
    With ActiveDocument
      For i = 0 To UBound(ArrFnd)
        StrPgs = StrPgs & vbCr & ArrFnd(i) & ": "
        With .Range
          With .Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindStop
            .MatchCase = True
            .MatchWholeWord = True
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
            .Text = ArrFnd(i)
            .Execute
          End With
          Do While .Find.Found
            StrPgs = StrPgs & .Information(wdActiveEndAdjustedPageNumber) & " "
            .Collapse wdCollapseEnd
            .Find.Execute
          Loop
        End With
      Next
    End With
    MsgBox StrPgs
    Application.ScreenUpdating = True
    End Sub


    Cheers
    Paul Edstein
    [MS MVP - Word]

    Saturday, August 8, 2015 5:11 AM
  • Hi Alaa

    Take a look at Paul's suggested approach, again, more specifically, at the Do While Find.Found loop.

    You need something like this if you search, do something, then want to search again.

    Normally, Find will go through the entire document, it would be unusual to want to start at the top of the document again. Indeed, if you're not altering the "found" text you'd land in a non-ending loop...

    I'm not clear why you're looping through the total number of pages? I normally would not expect that in a Find loop. Is it because you're worried about an endless loop? To control that, you should set the Wrap parameter of Find.Execute. It takes a WdFindWrap enum that controls how Word handles repeating the Find (or not) once the document has been searched.


    Cindy Meister, VSTO/Word MVP, my blog

    Sunday, August 9, 2015 1:40 PM
    Moderator

All replies

  • Try something based on the following VBA code:

    Sub Demo()
    Application.ScreenUpdating = False
    Dim ArrFnd, i As Long, StrPgs As String
    ArrFnd = Array("references", "contents", "abstract")
    With ActiveDocument
      For i = 0 To UBound(ArrFnd)
        StrPgs = StrPgs & vbCr & ArrFnd(i) & ": "
        With .Range
          With .Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindStop
            .MatchCase = True
            .MatchWholeWord = True
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
            .Text = ArrFnd(i)
            .Execute
          End With
          Do While .Find.Found
            StrPgs = StrPgs & .Information(wdActiveEndAdjustedPageNumber) & " "
            .Collapse wdCollapseEnd
            .Find.Execute
          Loop
        End With
      Next
    End With
    MsgBox StrPgs
    Application.ScreenUpdating = True
    End Sub


    Cheers
    Paul Edstein
    [MS MVP - Word]

    Saturday, August 8, 2015 5:11 AM
  • I think I know where my problem is 

    when the loop starts searching for the first word it scans the whole document and then starts the search for the 2nd word from where it stopped not starting from the beginning again, I found a way to go back GoBack()

    https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word._application.goback(v=office.14).aspx

    but it only goes last 3 locations which doesn't get accurate results. I don't know how to reset the range or if it's even possible.

    Saturday, August 8, 2015 12:12 PM
  • Hi Alaa

    Take a look at Paul's suggested approach, again, more specifically, at the Do While Find.Found loop.

    You need something like this if you search, do something, then want to search again.

    Normally, Find will go through the entire document, it would be unusual to want to start at the top of the document again. Indeed, if you're not altering the "found" text you'd land in a non-ending loop...

    I'm not clear why you're looping through the total number of pages? I normally would not expect that in a Find loop. Is it because you're worried about an endless loop? To control that, you should set the Wrap parameter of Find.Execute. It takes a WdFindWrap enum that controls how Word handles repeating the Find (or not) once the document has been searched.


    Cindy Meister, VSTO/Word MVP, my blog

    Sunday, August 9, 2015 1:40 PM
    Moderator