View Single Post
 
Old 01-10-2024, 03:59 AM
vivka vivka is offline Windows 7 64bit Office 2016
Expert
 
Join Date: Jul 2023
Posts: 302
vivka is on a distinguished road
Default

Hi! Good that you think you have found sth different from the codes proposed before. To retain the original selection, oRng.Duplicate could be used:
Code:
Sub Find_Wd_N_Select_Sent()
'Find the inputboxed wd & select the sentence it is in.
Dim oRng As range
Dim oRngD As range
Dim strWd As String
    
    Set oRng = selection.range
    Set oRngD = oRng.Duplicate
    strWd = InputBox("Enter the word to find", "FIND")
    With oRngD.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .text = strWd
        .Replacement.text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchWildcards = False
        If .Execute Then
            oRngD.Select
            selection.Extend: selection.Extend: selection.Extend
'Or using your .Expand:
 '            selection.Expand Unit:=3
'Or:
'            selection.Expand Unit:=wdSentence
         End If
    End With
'This is to see the original selection:
    oRng.Select
 '    Set oRng = Nothing
 End Sub
That's it. As simple as this. Run the code line-by-line pressing F8 to see how it works.
The final note: if you want to go on searching for the next occurrence of the key wd in the original selection, you will keep finding the 1st occurrence. So, collapasing the range is better, I think. Our side view is always better than other people's front view of the same thing. Good luck!
PS. Another challenge: If you try to use .Expand function to select the last or only sentence in a table cell, you will get a wrong selection.
Reply With Quote