View Single Post
 
Old 07-25-2025, 05:33 PM
June7's Avatar
June7 June7 is offline Windows 10 Office 2010
Novice
 
Join Date: Nov 2023
Posts: 23
June7 is on a distinguished road
Default

Search "outlook vba replace within selected text in email". CoPilot shows me code that invokes WordEditor object. Seems I've seen something like this long before AI. I've never coded behind Outlook so no idea how you establish a "button" to trigger code.

Here's the code as presented, not tested:
Code:
Sub ReplaceInSelectedText()
    Dim objInspector As Outlook.Inspector
    Dim objWordEditor As Object
    Dim objSelection As Object
    Dim selectedText As String
    Dim replacedText As String
    Dim searchText As String
    Dim replaceText As String

    ' Get the current Inspector
    Set objInspector = Application.ActiveInspector

    ' Ensure the Inspector is open and in compose mode
    If Not objInspector Is Nothing And objInspector.EditorType = olEditorWord Then
        ' Access the Word editor
        Set objWordEditor = objInspector.WordEditor
        Set objSelection = objWordEditor.Application.Selection

        ' Get the selected text
        selectedText = objSelection.Text

        ' Define the text to search for and replace
        searchText = "oldWord"  ' Replace with the word/phrase to search for
        replaceText = "newWord" ' Replace with the word/phrase to replace with

        ' Replace the text
        replacedText = Replace(selectedText, searchText, replaceText)

        ' Update the selection with the replaced text
        objSelection.Text = replacedText

        MsgBox "Text replaced successfully!", vbInformation
    Else
        MsgBox "Please ensure you are editing an email and have selected text.", vbExclamation
    End If
End Sub
Reply With Quote