2

我可以使用以下方法在选择之前和之后插入文本:

Selection.InsertBefore "start"
Selection.InsertAfter "end"

但我无法控制插入文本的样式。如何将新插入的文本设置为特定样式(并保持原来的选定文本不变)?

4

2 回答 2

5

下面是两个单独的代码来处理 Insert After 和 Insert Before。插入文本后,根据插入的位置,您必须选择插入的文本,然后更改样式。

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
于 2012-08-16T06:40:17.617 回答
1

这是一个简单的例子:

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
于 2012-08-16T18:54:13.297 回答