Search code examples
c#ms-wordoffice-interopword-addins

WordEditor remove blank lines at end of document


I am trying to detect and remove blank lines present in a specific range of a document using the below code:

    Document doc = appointmentItem.GetInspector.WordEditor as Microsoft.Office.Interop.Word.Document;
    Bookmark bmkFound = doc.Bookmarks.get_Item("bmkToClean");
    Range bmkFound = bmkFound.Range;
    Find find = bmkFound.Find;
    find.Text = "\r";
    find.Replacement.Text = "";
    find.Execute();
    find.Text = "\r\n";
    find.Replacement.Text = "";
    find.Execute();
    find.Text = Convert.ToChar(13).ToString();
    find.Replacement.Text = "";
    find.Execute();
    find.Text = Convert.ToChar(10).ToString();
    find.Replacement.Text = "";
    find.Execute();

    lastChar.Text.Replace(Convert.ToChar(13), '');
    lastChar.Text.Replace(Convert.ToChar(10), '');
    lastChar.Text.Replace("\r", "");
    lastChar.Text.Replace("\n", "");

Nothing worked out so far. Any hint?


Solution

  • OK, the issue was that I had several blank lines so the code needed the below adjustment:

    Document doc = appointmentItem.GetInspector.WordEditor as 
    Microsoft.Office.Interop.Word.Document;
    Bookmark bmkFound = doc.Bookmarks.get_Item("bmkToClean");
    Range bmkFound = bmkFound.Range;
    Find find = bmkFound.Find;
    find.Text = "\r";
    find.Replacement.Text = "";
    find.Forward = true;
    find.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;
    find.Replacement.Text = "";
    find.Execute(Replace: WdReplace.wdReplaceAll);