Created
October 25, 2019 08:43
-
-
Save supergrass71/71836b8ea3c15f31afea18443634bfc5 to your computer and use it in GitHub Desktop.
Find Replace Anywhere #Word
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Public Sub FindReplaceAnywhere() 'https://wordmvp.com/FAQs/Customization/ReplaceAnywhere.htm Dim rngStory As Word.Range Dim pFindTxt As String Dim pReplaceTxt As String Dim lngJunk As Long Dim oShp As Shape | |
pFindTxt = InputBox("Enter the text that you want to find.", "FIND") | |
If pFindTxt = "" Then | |
MsgBox "Cancelled by User" | |
Exit Sub | |
End If | |
TryAgain: pReplaceTxt = InputBox("Enter the replacement.", "REPLACE") | |
If pReplaceTxt = "" Then | |
If MsgBox("Do you just want to delete the found text?", vbYesNoCancel) = vbNo Then | |
GoTo TryAgain | |
ElseIf vbCancel Then | |
MsgBox "Cancelled by User." | |
Exit Sub | |
End If | |
End If | |
'Fix the skipped blank Header/Footer problem | |
lngJunk = ActiveDocument.Sections(1).Headers(1).Range.StoryType | |
'Iterate through all story types in the current document | |
For Each rngStory In ActiveDocument.StoryRanges | |
'Iterate through all linked stories | |
Do | |
SearchAndReplaceInStory rngStory, pFindTxt, pReplaceTxt | |
On Error Resume Next | |
Select Case rngStory.StoryType | |
Case 6, 7, 8, 9, 10, 11 | |
If rngStory.ShapeRange.Count > 0 Then | |
For Each oShp In rngStory.ShapeRange | |
If oShp.TextFrame.HasText Then | |
SearchAndReplaceInStory oShp.TextFrame.TextRange, pFindTxt, pReplaceTxt | |
End If | |
Next oShp | |
End If | |
Case Else | |
'Do Nothing | |
End Select | |
On Error GoTo 0 'Get next linked story (if any) | |
Set rngStory = rngStory.NextStoryRange | |
Loop Until rngStory Is Nothing | |
Next rngStory | |
End Sub | |
Public Sub SearchAndReplaceInStory(ByVal rngStory As Word.Range, _ | |
ByVal strSearch As String, ByVal strReplace As String) | |
With rngStory.Find | |
.ClearFormatting | |
.Replacement.ClearFormatting | |
.Text = strSearch | |
.Replacement.Text = strReplace | |
.Wrap = wdFindContinue | |
.Execute Replace:=wdReplaceAll | |
End With | |
End Sub | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment