创建节

创建节有两种方法,一种是使用Sections对象的Add方法创建,另一种是使用Range对象的InsertBreak方法创建。

使用Sections对象的Add方法创建

Sections对象的Add方法在指定字符序列前面添加一个分节符,其语法格式为:

code.vba
doc.Sections.Add Range, Type

其中,doc为当前使用的文档;Range参数为指定的字符序列,分节符在该字符序列前面插入,如果省略该参数,分节符在文档最后插入;Type为分节符的类型,取值为WdSectionStart常量之一,如表5-1中所示。

表5-1 WdSectionStart常量表示的分节符

分节符的类型 常 数
连续分节符 0 wdSectionContinuous
偶数页分节符 3 wdSectionEvenPage
新栏分节符 1 wdSectionNewColumn
新页分节符 2 wdSectionNewPage
奇数页分节符 4 wdSectionOddPage

下面打开文档test2.docx,获取第5个段落的字符序列,在该段落前添加一个下一页分节符。

code.vba
Sub Test()
  Dim doc As Document
  Set doc = Documents.Open("D:\test2.docx")
  Dim pg As Paragraph
  Set pg = doc.Paragraphs(5)
  doc.Sections.Add pg.Range, wdSectionNewPage
End Sub

使用Range对象的InsertBreak方法创建

用Range对象表示文档中指定节的范围,使用它的InsertBreak方法插入分节符。该方法的语法格式为:

code.vba
rng.InsertBreak Type

其中,Type表示要插入的分节符的类型,取值为wdBreakType常量之一,如表5-2中所示。

表5-2 wdBreakType常量表示的分节符

分节符的类型 常 数
连续分节符 3 wdSectionBreakContinuous
偶数页分节符 4 wdSectionBreakEvenPage
下一页分节符 2 wdSectionBreakNextPage
奇数页分节符 5 wdSectionBreakOddPage

下面将文档中第5个段落定义为一个字符序列,在字符序列前面插入下一页分节符。

code.vba
Sub Test2()
  Dim doc As Document
  Set doc = Documents.Open("D:\test2.docx")
  Dim pg As Paragraph
  Set pg = doc.Paragraphs(5)
  pg.Range.InsertBreak wdSectionBreakNextPage
End Sub