【发布时间】:2016-10-28 02:39:35
【问题描述】:
我的对象很简单 - 我想要一个快捷方式来用大写字符替换选择中的文本,而不应用“AllCaps”样式,原因我不会在这里讨论。
我已经成功地使用了Selection.Delete 和Selection.Insert,但这似乎并没有保留段落样式所固有的字体样式。
当我尝试使用 VBA Selection.Find.Execute:=ReplaceAll 时,它会替换整个文档中的所有实例。我知道这应该是.wrap=wdFindContinue 的行为,但我设置了.wrap=wdFindStop。我最好的猜测是,因为我的.text 被设置为调用Selection 对象的变量,所以在设置.text 时它会以某种方式丢失选择(尽管在我逐步执行代码时这在视觉上并不明显 - 选择保持突出显示),导致.ReplaceAll 为整个文档执行。如果我为特定情况手动输入“find”(.text)字符串,它只会在选择时执行(即使在 .Replacement.Text 字段中调用了变量txt!),但显然不会实用。
这是我的代码:
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
【问题讨论】: