次を使用して、選択範囲の前後にテキストを挿入できます。
Selection.InsertBefore "start"
Selection.InsertAfter "end"
しかし、挿入されたテキストのスタイルを制御することはできません。新しく挿入されたテキストを特定のスタイルに設定するにはどうすればよいですか (元の選択されたテキストはそのままにしておく)?
以下は、Insert After と Insert Before を処理する 2 つの別個のコードです。テキストを挿入したら、挿入された場所に応じて、挿入されたテキストを選択してからスタイルを変更する必要があります。
Sub InsertAfter()
Dim wrd As String
Dim rng As Range
wrd = "End"
Set rng = Selection.Range
rng.InsertAfter wrd
'~~> Remove selection. This will move the cursor at end of selected word
Selection.MoveRight Unit:=wdCharacter, Count:=1
'~~> Select the inserted word
Selection.MoveRight Unit:=wdCharacter, Count:=Len(wrd), Extend:=wdExtend
'~~> Change Style
Selection.Style = ActiveDocument.Styles("List Paragraph")
End Sub
Sub InsertBefore()
Dim wrd As String
Dim rng As Range
wrd = "Start"
Set rng = Selection.Range
rng.InsertBefore wrd
'~~> Remove selection. This will move the cursor at begining of inserted word
Selection.MoveLeft Unit:=wdCharacter, Count:=1
'~~> Select the inserted word
Selection.MoveRight Unit:=wdCharacter, Count:=Len(wrd), Extend:=wdExtend
'~~> Change Style
Selection.Style = ActiveDocument.Styles("List Paragraph")
End Sub
簡単な例を次に示します。
Sub test()
Dim StartingCount As Long
Dim InsertBeforeCount As Long
With ActiveDocument
StartingCount = .Characters.Count
Selection.InsertBefore "start"
InsertBeforeCount = .Characters.Count - StartingCount
.Range(1, InsertBeforeCount).Font.Bold = True
Selection.InsertAfter "end"
.Range(StartingCount + InsertBeforeCount, .Characters.Count).Font.Italic = True
End With
End Sub