My object is simple - I want a shortcut to replace text in a selection with uppercase characters, without applying the "AllCaps" style, for reasons I won't go into here.
I have succeeded by using Selection.Delete
and Selection.Insert
, but that doesn't seem to preserve font styles not inherent to the paragraph style.
When I try using VBA Selection.Find.Execute:=ReplaceAll
, it is replacing all instances in the entire document. I am aware that this should be the behavior for .wrap=wdFindContinue
, but I have set .wrap=wdFindStop
. My best guess is that because my .text
is set as a variable that calls the Selection
object, it loses the selection somehow when setting .text
(although visually this is not apparent when I step through the code - selection stays highlighted), resulting in .ReplaceAll
executing for the whole document. If I manually enter the "find" (.text
) string for a particular case, it executes on the selection only (even with the variable txt
called in the .Replacement.Text field!), but obviously that won't be practical.
Here is my code:
Option Explicit
Sub ReplaceWithUppercase()
Dim pasteAutoFormatSetting As Boolean
Dim txt As String
'Save current user selection of whether to adjust spacing automatically when pasting:
pasteAutoFormatSetting = Options.PasteAdjustWordSpacing
'Turn off auto spacing adjustment:
Options.PasteAdjustWordSpacing = False
txt = Selection.Range.text
With Selection.Font
.AllCaps = False
End With
'The next two lines work but do not seem to preserve built-in font styles
'already applied to the selected text, so I wanted to instead use find/replace:
'Selection.Range.Delete
'Selection.Range.InsertAfter (UCase(txt))
With Selection.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.text = txt
.Replacement.text = UCase(txt)
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
'Return to user preference for auto apacing adjustment:
Options.PasteAdjustWordSpacing = pasteAutoFormatSetting
End Sub