2011-10-02 89 views
2

我一直在试图找出如何前和使用VBA在Word中一个给定的风格后,插入文本。在VBA中,如何在样式之前和之后插入文本?

目前我通过文件运行从上到下,找到风格,并进行插入。这是时间消耗和不雅(至少可以说)。

应该可以使用Range对象和 Selection.InsertBefore() 和 Selection.InsertAfter() 但我不能得到它的工作。

有谁知道如何做到这一点?

这第二编辑给的那种我要寻找的东西的一个更好的主意,但将需要修改,以找到一个特定的风格:

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 

另一种方式,也许可以FO这个,通过使用通配符和样式,但是当我使用(*)时,它只能找到一个带有样式的字符,而不是整个字符串。

也许有一些办法使它发现整个字符串?然后,将有可能做一个与“mytext1”“全部替换” \ 1“mytext2”

+1

这将有助于张贴你现在的代码。 .. –

回答

1

Word有一个功能来查找与某些风格替换文本,所以你甚至不需要一个宏。但是,如果你想将它与VBA自动化,下面的示例代码插入FOO在任何Heading 2 -styled代码前,追加酒吧算账:

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

非常感谢乔尔,那正是我所期待的。我非常感谢。 – Anandajoti

相关问题