Search code examples
c#ms-wordword-automationword-interop

Word interop apply style to all the matches


I have written code to find citations in the word file and trying to make all the citations superscript.

Word.Range rngCitations = doc.Content;
        rngCitations.Find.MatchWildcards = true;
        rngCitations.Find.Text = @"(\[[0-9]{1,}[,0-9]*\])";
        if (rngCitations.Find.Execute())
        {
            rngCitations.Font.Superscript = 1;
            rngCitations.Font.Bold = 1;

         }

But, only first match updating to Superscript. How do I change this code to apply styling to all the matches.


Solution

  • To loop you can use the official example: https://learn.microsoft.com/en-us/visualstudio/vsto/how-to-programmatically-loop-through-found-items-in-documents?view=vs-2019

    rng.Find.ClearFormatting(); 
    rng.Find.Forward = true; 
    rng.Find.Text = "find me"; 
    
    rng.Find.Execute(
        ref missing, ref missing, ref missing, ref missing, ref missing, 
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing);
    
    while (rng.Find.Found) 
    { 
        intFound++;
        rng.Find.Execute(
            ref missing, ref missing, ref missing, ref missing, ref missing, 
            ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing);
    }
    

    In your case change if with while

    while (rngCitations.Find.Execute())
    {
          rngCitations.Font.Superscript = 1;
          rngCitations.Font.Bold = 1;
    }