0
votes

Trying to search a word document through excel VBA and delete the found text:

 Set objWord = CreateObject("Word.Application")

    objWord.Visible = True
    path = "C:\Test.docx"
    txt1 = "Search text"
    Set objDoc = objWord.Documents.Open(path)


    With objWord.ActiveDocument
        Set myRange = .Content
        With myRange.Find
            .Text = txt1
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .Execute

            Selection.Delete

        End With
    End With

However, it doesn't seem to delete the text!

Any help please

1
What Vityata says... If you were doing objWord.Selection.Find (which I don't recomment) then Selection.Delete ought to work, as long as Find was successful - otherwise something else would be deleted. myRange.Delete would also work, as long as you test whether Find.Execute returns True. So on the whole, Vityata's suggestion is the best way. - Cindy Meister
@CindyMeister Could you give an example with the delete? I can't seem to get it to work. - user33484
Looking at your comment to Vityata: What do you mean by "line"? An empty paragraph? What you search is standing in its own paragraph and deleting it leaves the paragraph? Then try searchig txt1 & ^p - Cindy Meister
@CindyMeister Yes exactly that, it leaves the paragraph. Your fix worked - thanks!! - user33484

1 Answers

1
votes

Selection.Delete works pretty well - it deletes the selected text. In your case, you are not selecting anything, thus nothing is deleted.

Try to execute the replacement like this:

Set objDoc = objWord.Documents.Open(path)
With objDoc.Content.Find
    .Text = txt1
    .Replacement.Text = ""
    .Wrap = wdFindContinue
    .Execute Replace:=wdReplaceAll, Forward:=True
End With

MSDN Finding and Replacing Text