PDA

View Full Version : [SOLVED:] Find Replace help



Kilroy
09-17-2018, 12:23 PM
I'm trying to get this macro to work. I've wasted so much time. Can someone let me know if it's possible? I'm trying to delete certain words but only from a specified table and column. The selection works but then fails after the first word. Any Ideas?


Sub DeleteMultipleWords()
Dim arr() As Variant
Dim i As Byte
'Sub PrepareForKeyWordSearch()

j = InputBox("Which Table?")
l = InputBox("Which Column?")
selection.Tables(j).Columns(l).Select
selection.Find.ClearFormatting
selection.Find.Replacement.ClearFormatting
arr = Array("for", "and", "not", "nor", "but", "or")

For i = LBound(arr) To UBound(arr)
With selection.Find
.Text = arr(i)
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
End With
selection.Find.Execute Replace:=wdReplaceAll
Next
End Sub

gmaxey
09-17-2018, 01:18 PM
Try:


Sub DeleteMultipleWords()
Dim arrWords()
Dim lngIndex As Long, lngTable As Long, lngCol As Long, lngRow As Long
Dim oRngCol As Range, oRng As Range
lngTable = InputBox("Which Table?")
lngCol = InputBox("Which Column?")
arrWords = Array("for", "and", "not", "nor", "but", "or")
Set oRng = ActiveDocument.Range
With oRng.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
For lngIndex = LBound(arrWords) To UBound(arrWords)
With ActiveDocument.Tables(lngTable)
For lngRow = 1 To .Rows.Count
Set oRngCol = .Cell(lngRow, lngCol).Range
Set oRng = .Cell(lngRow, lngCol).Range
With oRng
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = arrWords(lngIndex)
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While .Execute
If oRng.Duplicate.InRange(oRngCol) Then
oRng.Text = ""
oRng.Collapse wdCollapseEnd
Else
Exit Do
End If
Loop
End With
End With
Next lngRow
End With
Next lngIndex
lbl_Exit:
Exit Sub
End Sub

Kilroy
09-17-2018, 01:30 PM
Perfect, Thanks Greg. Much appreciated.

techpub
01-21-2019, 01:13 AM
Hi Greg, hope it's ok to ask a question about this code. I'm self taught here. Two questions if I may 1) the find replace at the beginning that searches for nothing and replaces nothing is that to "wipe the slate clean" for the find and replace further down? 2) MOST CURIOUS ABOUT, i like using ranges but have never used the syntax "oRng.Duplicate.InRange" . What does the Duplicate.InRange do? Thank you, Kyle.