none
How to remove all the double spaces with a single space in the word document? RRS feed

  • Question

  • I am developing a VSTO addin in for word 2013.

    I am wondering how i can replace all the double spaces in the document with a single space?

    I tried the below and it is not working.

               Word.Range rng = app.ActiveDocument.Range();
                rng.Find.Text = "[ ]{2,}";
                rng.Find.Replacement.Text = "[ ]";
                rng.Find.Execute(Replace: Word.WdReplace.wdReplaceAll);

    thank you in advance.

    Lavnaya

    Thursday, February 11, 2016 6:11 PM

Answers

  • Please never mind. I answered my own question. 

               Word.Range rng = app.ActiveDocument.Range();
                rng.Find.Text = "  ";
                rng.Find.Replacement.Text = " ";
                rng.Find.Execute(Replace: Word.WdReplace.wdReplaceAll);

    Thursday, February 11, 2016 6:14 PM
  • Your revised code would not reduce three or more spaces to one. What you needed with your first attempt was to use the 'MatchWildcards' method - and to not include the [ or ] in the replacement expression. For example:

    Word.Range rng = app.ActiveDocument.Range();
    rng.Find.Text = "[ ]{2,}";
    rng.Find.Replacement.Text = " ";
    rng.Find.MatchWildcards = True;
    rng.Find.Execute(Replace: Word.WdReplace.wdReplaceAll);

    The line 'rng.Find.MatchWildcards = True;' might not be quite right (I don't use VSTO), but it should be close.


    Cheers
    Paul Edstein
    [MS MVP - Word]

    Friday, February 12, 2016 12:48 AM

All replies

  • Please never mind. I answered my own question. 

               Word.Range rng = app.ActiveDocument.Range();
                rng.Find.Text = "  ";
                rng.Find.Replacement.Text = " ";
                rng.Find.Execute(Replace: Word.WdReplace.wdReplaceAll);

    Thursday, February 11, 2016 6:14 PM
  • Your revised code would not reduce three or more spaces to one. What you needed with your first attempt was to use the 'MatchWildcards' method - and to not include the [ or ] in the replacement expression. For example:

    Word.Range rng = app.ActiveDocument.Range();
    rng.Find.Text = "[ ]{2,}";
    rng.Find.Replacement.Text = " ";
    rng.Find.MatchWildcards = True;
    rng.Find.Execute(Replace: Word.WdReplace.wdReplaceAll);

    The line 'rng.Find.MatchWildcards = True;' might not be quite right (I don't use VSTO), but it should be close.


    Cheers
    Paul Edstein
    [MS MVP - Word]

    Friday, February 12, 2016 12:48 AM