如何使用VB格式化Microsoft(MS)Word 2007中的域代码?

时间:2012-08-20 17:29:58

标签: vb.net ms-word

我正在尝试插入一个引用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)

现在书签设置在文档的顶部。假设我们现在只有几页进入doc。

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

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

1 个答案:

答案 0 :(得分: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中是一种很好的做法)。