オブジェクトはシンプルです - 選択肢のテキストを大文字で置き換えるショートカットを「AllCaps」スタイルを適用せずにここでは行いません。Word VBAは大文字でのみ選択項目に表示されるテキストを置き換えます
私はSelection.Delete
とSelection.Insert
を使用して成功しましたが、段落スタイルに固有のフォントスタイルは保持されていないようです。
VBA Selection.Find.Execute:=ReplaceAll
を使用すると、ドキュメント全体のすべてのインスタンスが置き換えられます。私はこれが.wrap=wdFindContinue
の振る舞いでなければならないことを認識していますが、.wrap=wdFindStop
を設定しました。私の最高の推測では、.text
がSelection
オブジェクトを呼び出す変数として設定されているため、が実行される結果、.text
を設定すると何とか選択が失われます(コード選択をステップ実行すると視覚的には明らかになりません)。文書全体について。特定のケースの "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
選択範囲の配列使っ
私は1行のマクロが好きです、ありがとう! 「検索」テキストが選択定義の文字列変数である場合にのみ選択項目でwdReplaceAllを実行できるかどうかは不明ですが、「Selection.Text = someString'。 – PatentWookiee
PatentWookiee、これはあなたの質問に反応するかどうかはわかりませんが、確かに使用することができます: 'Selection.Text = Replace(" abcdefg "、" cde "、" CDE ")" abCDEfg "を返すもの –
いいでしょうかそのReplace関数の引数として正規表現を使うことができますが、私はVBAではないと推測しています。私は、正規表現を使用してテキストを検索して置き換えるマクロを書いていますが、それらはむしろ長年巻き込まれています: – PatentWookiee