Range.Delete method when deleting hyphenated words inserts blanks RRS feed

  • Question

  • Hi All,

    I'm attempting to delete words in a sentence via my VSTO AddIn (Win7/Office 10/VS 10).

    the sentence is:  "We work day-by-day on the project."

    and I want to delete "day-by-day".

    the code instruction is:

    Globals.ThisAddIn.Application.ActiveWindow.Selection.Sentences[0].Words[3].Delete(Word.WdUnits.wdWord, 5);

    However, the results are that the "Delete" method results in:

    day- (deleted)

    <space> (inserted)

    by- (deleted)

    resulting sentence is:  "We work  day on the project." with two spaces between "word" and "day".

    How come??  Why the insert of a blank?  Why not delete the last word "day".  The count is off.

    Any workaround suggestions??

    Thanks, billwa992

    Tuesday, November 22, 2011 11:30 PM

All replies

  • Hi Bill,

    I don't know how the code works (delete words at least) on your side. For me, your code throw an exception as all enumerations of Office object is 1-based rather than 0-based. So after changing the code to:


    Globals.ThisAddIn.Application.ActiveWindow.Selection.Sentences[1].Words[3].Delete(Word.WdUnits.wdWord, 5);

    The code works as what it is expected.


    BTW, I'm also using Office 2010/VS2010/Windows7.

    Good day,

    Calvin Gao[MSFT]
    MSDN Community Support | Feedback to us

    Wednesday, November 23, 2011 9:24 AM
  • Calvin,

    Sorry, the 0 was a transformation error.  So when you do it, it actually deletes the entire hyphenated word combo without inserting those silly blanks??


    Monday, November 28, 2011 7:59 PM
  • Calvin,

    So I've copied a VS2010 Project Folder (in a zip file) up to my skydrive's public folder (  First time I've done this so let me know if you have problems accessing the file or my skydrive and if so, maybe what I need to do so you can access it.

    Bill has a file to share with you on SkyDrive. To view it, click the link below.

    Expand Test

    Anyways, the file's name is "Hyphen".  It contains a simple AddIn project that has a custom ribbon with a single button.  The test document to open in word is in the project folder "Hyphen Test.docx".  I also provided an example of the output file with Track Changes saved "Hyphen Test Output.docx" that shows that when deleting 5 words that consist of a hyphenated combo, the five words are not deleted, but actually a "blank space" is inserted and only the first word and hyphen and the second word and hypen are deleted, but not the fifth word "day".

    Hope this helps.  Let me know your thoughts.

    THX, billwa992

    • Edited by billwa992 Thursday, December 8, 2011 8:08 AM
    Monday, November 28, 2011 9:57 PM
  • I have deleted this post because the forum would not correctly format the code block (no matter what I tried). I have reposted below, where the code block is correctly formatted (in colors).


    • Edited by Geoff_G Thursday, December 8, 2011 12:22 PM
    Thursday, December 8, 2011 1:17 AM
  • (I am reposting this in an attempt to get the code block formatted correctly.)

    I hope the following VBA demo might help.


    Public Sub DeletePhrase()
        '   Declare constant:
        '   Store phrase to be deleted:
        Const strcTextToFind = "day-by-day"
        '   Declare object variables:
        Dim objDOC As Word.Document
        Dim objRNG As Word.Range
        Dim objFND As Word.Find
        '   Declare other working variables:
        Dim fFound As Boolean
        '   Instantiate objects:
        Set objDOC = Word.Application.ActiveDocument
        Set objRNG = objDOC.Sentences(1)
        Set objFND = objRNG.Find
        '   Remove the leading apostrophe from the
        '   following two code lines if you want to
        '   stop and inspect the document to verify
        '   that the range object now spans the
        '   first sentence; then return here and
        '   press F5 to continue.
        '   Delete the following two code lines when
        '   you're satisfied the code works OK.
    '    objRNG.Select
    '    Stop
        '   Use the FIND object:
        With objFND
            '   Set all relevant properties of the find object
            '   to specify the criteria for the find:
            .Forward = True
            .Text = strcTextToFind
            .MatchCase = True
            .MatchWholeWord = True
            '   Call the Execute method of the Find object
            '   and capture its Boolean return value:
            fFound = .Execute
        End With
        '   See if the text was found:
        If fFound Then
            '   Text was found.
            '   Move start and end of range object to the
            '   beginning and end of the text:
            objRNG.MoveStartUntil strcTextToFind
            '   Move the end of the range object to include
            '   any trailing space characters:
            objRNG.MoveEndWhile " "
            '   Remove the leading apostrophe from the
            '   following two code lines if you want to
            '   stop and inspect the document to verify
            '   that the range object now spans the
            '   text to be deleted; then return here and
            '   press F5 to continue.
            '   Delete the following two code lines when
            '   you're satisfied the code works OK.
    '        objRNG.Select
    '        Stop
            '   Delete the text in the range object:
            '   Show message:
            MsgBox "Text:" & vbTab & strcTextToFind _
                & vbNewLine & vbNewLine _
                & "The above text was deleted.", _
                vbOKOnly + vbInformation, _
                "Program Finished" & Space(50)
            GoTo Exit_TestWordDelete
            '   The text was not found.
            MsgBox "Find:" & vbTab & strcTextToFind _
                & vbNewLine & vbNewLine _
                & "The above text was not found.", _
                vbExclamation + vbOKOnly, _
                "Program Finished" & Space(50)
            GoTo Exit_TestWordDelete
        End If
        '   Ignore errors while destroying objects:
        On Error Resume Next
        Set objFND = Nothing
        Set objRNG = Nothing
        Set objDOC = Nothing
        Exit Sub
    End Sub




    Thursday, December 8, 2011 12:19 PM
  • Geoff,

    Thanks for the reply.  However, that doesn't really point out what I might be doing wrong (if anything).  My skydrive post has an example that consistently fails (in c#).


    Wednesday, February 8, 2012 6:10 PM
  • Bill,

    I took a look at your SkyDrive but I'm not familiar with C# so cannot help there.

    I hoped the VBA example might offer an alternative approach.

    Your first post wondered why an extra space had been inserted. 

    I suggest you use the Select method while debugging to see what, exactly, gets selected before deletion.  For example, would something like the following select "day " at the end of "day-by-day " (notice inclusion of the trailing space after "day ")?


    The point of suggesting the above is that, if, in your application, Word is not selecting the trailing space, then it would seem that your suspicion that Word is inserting an extra space isn't actually the right diagnosis of what's going on.  In VBA, the definition of a word *does* include the trailing space(s).  Therefore, it seems, so should your use of Word and, therefore, the trailing space *should* be deleted.  However, I'm wondering if, in your application, Word is not actually *inserting* an extra space, but is not selecting the trailing space for deletion.  Whatever is happening, it seems odd!

    A couple of months ago, I took a look at your other post about selecting sentences and decided that there are so many different ways a sentence can end that it would be impossible to reflect all those possibilities — and Word clearly doesn't.  If memory serves me right, for your purposes, Word's ideas of what constitute a sentence did not include all the ways in which you had sentences ending and, therefore, your application was not working as expected.  It seemed to me at the time that, because it would be impossible to account for all the different ways in which sentences can end, it would be better (if possible) to develop a different approach.  I guess the Word developers at Microsoft have taken into account all sentence types they think are sensible, but they probably cannot account for every possibility — as I guess neither can you.  I find that making heavy use of multiple Range objects can usually provide a solution.  The Range.Duplicate method is very useful for providing a second independent range object pointing to the same start and end positions as an existing range object. And sometimes, using multiple range objects works!  I tend to avoid the Selection object altogether.  The best book I've seen on programming Word using VBA is by Steven Roman, but I don't know if that would give you the clues you need in C#.

    Sorry, I don't know the answer to your problems. 


    • Proposed as answer by Test Wordrake Sunday, April 15, 2012 6:44 PM
    Wednesday, February 8, 2012 7:54 PM
  • Geoff,

    Thanks for your assist with this.  We've moved on to shipping and simply ignoring this problem for the time being (the pressures of the software business).  I do appreciate your thoughts on this and will refer back to them when we begin work on the next version.


    Sunday, April 15, 2012 6:44 PM
  • When deleting some strings using VBA, I find that the delete method somethimes inserts a space where the deleted text was. A workaround is to replace the unwanted text with a null string. A similar approach may be what you need.

    Paul Edstein
    [MS MVP - Word]

    Monday, April 16, 2012 12:25 AM
  • I'm using Office 2016, and the same problem still exists.... very annoying, even worse, it is intermittent, it doesn't happen every time!


    Thursday, June 23, 2016 9:48 PM
  • Ok, work around for me was to instead just replace the range with ""

    e.g.     rWordRange.Text = ""

    (instead of rWordRange.Delete)


    Thursday, June 23, 2016 10:08 PM