Microsoft Word Find and Replace VBA (Visual Basic for Applications)

Microsoft Word Find and Replace VBA (Visual Basic for Applications)

Replacement

Represents the replace criteria for a find-and-replace operation. The properties and methods of the Replacement object correspond to the options in the Find and Replace dialog box.

The following example replaces the next occurrence of the word “VBA” with the word “VBAOVERALL.”

Source String

Code example

Public Sub FindAndReplace()
    'Retain selection
    Dim oRange As Range
    Set oRange = Selection.Range
    
    'Perform find replace step by step
    oRange.Find.Text = "VBA"
    oRange.Find.ClearFormatting
    oRange.Find.Replacement.Text = "VBAOVERALL"
    oRange.Find.Replacement.ClearFormatting
    oRange.Find.Execute Replace:=wdReplaceOne, Forward:=True
End Sub

Output

Formatting Replacement

To find and replace formatting, set both the find text and the replace text to empty strings (“”) and set the Format argument of the Execute method to True. The following example removes all the bold formatting in the active document. The Bold property is True for the Find object and False for the Replacement object.

Code example

Public Sub FindReplace()
    'Retain selection
    Dim oRange As Range
    Set oRange = Selection.Range
    
    'Perform find replace formatting
    oRange.Find.ClearFormatting
    oRange.Find.Font.Bold = True
    oRange.Find.Text = ""
    
    'Replacement
    oRange.Find.Replacement.ClearFormatting
    oRange.Find.Replacement.Font.Bold = False
    oRange.Find.Replacement.Text = ""
    
    'Execute formatting
    oRange.Find.Execute Format:=True, Replace:=wdReplaceAll
End Sub

Output

Please leave your comments or queries under comment section also please do subscribe to out blogs to keep your self upto date.

Leave a Reply

Your email address will not be published. Required fields are marked *