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

问题描述 投票:0回答:1

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

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

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

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

vba ms-word word-vba
1个回答
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")来改变,但这只会改变书签的字体,而不是新插入的文本。

© www.soinside.com 2019 - 2024. All rights reserved.