Insert text before and after selection and set style of new text

*爱你&永不变心* 提交于 2019-12-24 01:17:51

问题


I can insert text before and after the selection using:

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

But I have no control over the style of the inserted text. How can I set the new, inserted text to a specific style (and leave the original selected text as it is)?


回答1:


Below are two separate code to handle Insert After and Insert Before. Once you insert the text then depending on where is it inserted you have to select the inserted text and then change the style.

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



回答2:


Here's a simple example:

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


来源:https://stackoverflow.com/questions/11980728/insert-text-before-and-after-selection-and-set-style-of-new-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!