Question

In my code below, when the word isn't there, all the table contente is deleted. How to fix it? Text is in Cell(1,1) for multiple tables.

Sub DeleteText()

StartWord = "Orientation:"
For Each oTbl In ActiveDocument.Tables
Set oRng = oTbl.Range

With oRng
.Find.Execute Findtext:=StartWord & "*", MatchWildcards:=True
.MoveStart wdCharacter, 0
.MoveEndUntil vbCr
.Delete

 End With
 Next
End Sub
Was it helpful?

Solution

First of all you need to add if statement which will check if your text is found. You will find that in the code below. However, I also improved the way you delete the whole content of cell where your text is found. My solution is better in situation when you have more lines/paragraphs/sentences in the cell.

Sub DeleteText_Improved()

Dim StartWord As String
Dim oTbl As Table
Dim oRng As Range

StartWord = "Mauris"

For Each oTbl In ActiveDocument.Tables
Set oRng = oTbl.Range

With oRng
.Find.Execute Findtext:=StartWord & "*", MatchWildcards:=True
If .Find.Found Then
    'how to select whole cell range
    oTbl.Cell(.Information(wdEndOfRangeRowNumber), _
            .Information(wdEndOfRangeColumnNumber)).Range.Delete

End If
End With
Next
End Sub

Final remark- your code is working only for the first occurrence of the word you search for. It will not remove other cells where the word appears.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top