开发者

In VBA, how to insert text before and after style?

开发者 https://www.devze.com 2023-04-10 05:29 出处:网络
I have been trying to work out how to insert text before and after a given style in Word using VBA. At present I run through the document from 开发者_如何转开发top to bottom, find the style, and mak

I have been trying to work out how to insert text before and after a given style in Word using VBA.

At present I run through the document from 开发者_如何转开发top to bottom, find the style, and make the insertions. It is time-consuing and inelegant (to say the least).

It should be possible to use a Range object and Selection.InsertBefore () and Selection.InsertAfter () but I can't get it to work.

Does anyone know how to do this?

This a second edit to give a better idea of the sort of thing I am looking for, but would need it modified to find a particular style:

Sub InsertBeforeMethod()
Dim MyText As String
Dim MyRange As Object
Set MyRange = ActiveDocument.Range
MyText = "<Replace this with your text>"
' Selection Example:
Selection.InsertBefore (MyText)
' Range Example: Inserts text at the beginning
' of the active document.
MyRange.InsertBefore (MyText)
End Sub

Another way it might be possible to fo this, is through using wildcards and style, but when I use (*) it only finds one character with the style, not the whole string.

Maybe there is some way to make it find the whole string? Then it would be possible to do a "replace all" with "mytext1"\1"mytext2"


Word has a feature to find and replace text with certain styles, so you don't even need a macro. But if you wish to automate it with VBA, the following sample code inserts foo in front of any Heading 2-styled code and appends bar afterwards:

Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles("Heading 2")
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = ""
    .Replacement.Text = "foo^&bar"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号