【问题标题】:How to insert text at a bookmark with keeping style in Microsoft Word with VBA?如何在带有 VBA 的 Microsoft Word 中保持样式的书签中插入文本?
【发布时间】:2015-08-12 04:50:10
【问题描述】:

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

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

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

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

【问题讨论】:

  • 是的。到目前为止,您尝试过什么?
  • 感谢 Olle 的提问。我知道 wdApp.Selection.Range.Font.Name = "Times New Roman" 应该与光标选择一起使用。但是,我插入带有书签的文本。是否可以选择插入的文本作为选择或类似 Bookmarks(myTextMark).Font.Name = "Times New Roman"?

标签: vba ms-word


【解决方案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")来更改,但这只会更改书签的字体,而不是新插入的文本。

【讨论】:

  • @hadesmajesty 如果解决了您的问题,请将答案标记为正确。
猜你喜欢
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 2010-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多