vba 在选择前后插入文本并设置新文本的样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11980728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert text before and after selection and set style of new text
提问by Flash
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)?
但我无法控制插入文本的样式。如何将新插入的文本设置为特定样式(并保持原始选定文本不变)?
回答by Siddharth Rout
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.
下面是两个单独的代码来处理 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
回答by Doug Glancy
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