#1
|
|||
|
|||
Applying a VBA code only on a selected text or range
Hello everyone,
I want to find and replace certain word in selected range of text only, Also, if I don't select anything, a message appear "Please select the range first", in order to prevent find and replace on entire document by mistake. Code:
Sub ReplaceName() ' 'Find what Format: Selection.Find.ClearFormatting ' Replace with Format: Selection.Find.Replacement.ClearFormatting With Selection.Find .Text = "Jhon" .Replacement.Text = "Robert" .Forward = True .Wrap = wdFindContinue .Format = True .MatchCase = False .MatchWholeWord = False .MatchKashida = False .MatchDiacritics = False .MatchAlefHamza = False .MatchControl = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False End With Selection.Find.Execute Replace:=wdReplaceAll End Sub |
#2
|
||||
|
||||
That's fairly straightforward and I assume you know that you have spelled 'John' incorrectly?
You only need to change the line Code:
.Wrap = wdFindContinue Code:
.Wrap = wdFindStop Code:
Sub ReplaceName() Dim oRng As Range If Len(Selection.Range) = 0 Then MsgBox "Select the text first", vbCritical Exit Sub End If Set oRng = Selection.Range With oRng.Find .ClearFormatting .Replacement.ClearFormatting .Text = "Jhon" .Replacement.Text = "Robert" .Forward = True .Wrap = wdFindStop .Format = True .MatchCase = False .MatchWholeWord = False .MatchKashida = False .MatchDiacritics = False .MatchAlefHamza = False .MatchControl = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False .Execute Replace:=wdReplaceAll End With Set oRng = Nothing End Sub
__________________
Graham Mayor - MS MVP (Word) (2002-2019) Visit my web site for more programming tips and ready made processes www.gmayor.com |
#3
|
|||
|
|||
Quote:
However, Thank you so much Best Regards with special thanks |
Tags |
find & replace, vba, word vba |
Thread Tools | |
Display Modes | |
|
Similar Threads | ||||
Thread | Thread Starter | Forum | Replies | Last Post |
Vertically Center Selected Range in the Useable Window | gmaxey | Word VBA | 0 | 12-19-2020 10:01 AM |
Find and Replace Selected Text or Macro for finding selected text | mrplastic | Word VBA | 4 | 12-20-2019 01:25 PM |
Set Range based on selected rows. | 14spar15 | Excel Programming | 8 | 11-19-2018 08:08 AM |
Two problems: Applying bold affects other tables and canvas doesn't appear at specified range | slaycock | Word VBA | 6 | 12-08-2016 02:28 AM |
Import a specific range (bookmarked section) from all Word docs in a selected folder | Greengecko | Word VBA | 5 | 06-14-2016 07:54 AM |