0

我正在尝试在 MS word 2007 的句子中间插入一个引用书签的域代码。我希望域代码为粗体和斜体,但未能成功使用 vb 格式化域代码。

这就是我所拥有的,它似乎应该可以工作,但事实并非如此。

Private WithEvents wordApp As Word.Application = New Word.Application
Private doc As Word.Document = wordApp.Documents.Add()
Dim bmRange As Word.Range = Nothing
Dim s As Word.Selection = wordApp.Selection

With s
  .Style = "Normal"
  .TypeText("THIS IS THE COURSE TITLE")
  .Collapse(Word.WdCollapseDirection.wdCollapseEnd)
  .StartOf(Word.WdUnits.wdSentence, Word.WdMovementType.wdExtend)
  bmRange = .Range
  .Collapse(Word.WdCollapseDirection.wdCollapseEnd)
  .TypeParagraph()
  .Collapse(Word.WdCollapseDirection.wdCollapseEnd)
End With

doc.Bookmarks.Add("CourseTitle", bmRange)

现在书签设置在文档的顶部。假设我们现在是文档的几页。

s = wordApp.Selection
With s
   .Style = "Normal"
   .TypeText("This is the first part of the sentence ")
   With .Range
     .Collapse(Word.WdCollapseDirection.wdCollapseEnd)
     .Fields.Add(s.Range, Word.WdFieldType.wdFieldEmpty, "REF CourseTitle", True)
     .Font.Bold = -1
     .Font.Italic = -1
     .Collapse(Word.WdCollapseDirection.wdCollapseEnd)
     .Font.Bold = 0
     .Font.Italic = 0
   End With
   .TypeText(" this is the rest of the sentence.")
End With

这会将域代码放置在我想要的位置,但不会对其进行格式化。有什么建议么?

4

1 回答 1

0

从您的第二段代码开始,以下内容可能会执行您想要的操作:

Dim f as Word.Field
s = wordApp.Selection
With s
   .Style = "Normal"
   .TypeText("This is the first part of the sentence ")
   With .Range
     .Collapse(Word.WdCollapseDirection.wdCollapseEnd)
     f = .Fields.Add(s.Range, Word.WdFieldType.wdFieldEmpty, "REF CourseTitle", True)
     f.Result.Bold = -1
     f.Result.Italic = -1
     .Collapse(Word.WdCollapseDirection.wdCollapseEnd)
   End With
   .TypeText(" this is the rest of the sentence.")
End With

我可能会在代码中更改其他内容,例如在代码的前面从 Selection 中获取 Range 对象,然后优先使用 Selection 对象。(不是必需的,但在 Word 中是一个很好的做法)。

于 2012-08-22T09:56:58.023 回答