如何在带有VBA的Microsoft Word中保留样式的书签中插入文本?

时间:2015-05-29 10:44:03

标签: vba ms-word word-vba

我在word文档中设置了某些书签,我想从txt文件中插入文本。以下是我的代码:

ActiveDocument.Bookmarks(myTextMark).Range.InsertFile FileName:=locations, ConfirmConversions:=False

我发现插入的文字是我单词的默认设置。

是否可以使用字体名称,大小,颜色设置插入的文本,并设置段落缩进?

1 个答案:

答案 0 :(得分:1)

我无法分辨,因为您没有在InsertFile示例中包含足够的代码,但我猜您的代码会替换文档中的书签。这使得很难在插入文本的位置添加地址。这里的技巧是弄清楚要更改字体的文档的哪个部分。这可以通过多种方式完成。

我建议如下,在书签后首先将光标设置为,然后插入文本。这样,插入文本后书签仍然存在,您可以将其与当前位置一起使用以仅插入插入的文本:

Option Explicit

Sub InsertAndUpdateText()
    Const myTextMark = 1
    Const locations = "C:\test.txt"

    '***** Select bookmark
    ActiveDocument.Bookmarks(myTextMark).Range.Select
    '***** Set the cursor to the end of the bookmark range
    Selection.Collapse Direction:=WdCollapseDirection.wdCollapseEnd
    '***** Insert text
    Selection.InsertFile FileName:=locations, ConfirmConversions:=False

    '***** Create new Range object
    Dim oRng As Range

    '***** Set oRng to text between the end of the bookmark and the start of the current position
    Set oRng = ActiveDocument.Range(ActiveDocument.Bookmarks(myTextMark).Range.End, Selection.Range.Start)

    '***** Do whatever with the new range
    oRng.Style = ActiveDocument.Styles("Normal")
    oRng.Font.Name = "Times New Roman"

    Set oRng = Nothing
End Sub

顺便说一句,关于你的评论,书签的字体也可以通过使用你用来插入文本的相同范围对象来改变(即ActiveDocument.Bookmarks(myTextMark).Range.Font = "Times New Roman"),但这只会改变书签的字体,不是新插入的文字。