在 Word VBA 開發中,Sections 集合與 Section 物件是控制文件版面配置(頁邊距、紙張大小、頁眉頁腳等)的核心。本文彙整常用屬性、方法與程式碼範例,供具備 VBA 基礎的開發者快速查閱。
ActiveDocument.Sections:取得目前文件的所有區段集合。Section:代表單一區段,透過索引(1-based)或 First/Last 屬性存取。PageSetup:區段的頁面設定物件,控制實際列印版面。' 第一區段
Dim secFirst As Section
Set secFirst = ActiveDocument.Sections.First
' 第二區段
Dim secSecond As Section
Set secSecond = ActiveDocument.Sections.Item(2)
' 最後一區段
Dim secLast As Section
Set secLast = ActiveDocument.Sections.Last
With secFirst.PageSetup
.TopMargin = CentimetersToPoints(2.54) ' 上邊距 2.54 cm
.BottomMargin = CentimetersToPoints(2.54) ' 下邊距
.LeftMargin = CentimetersToPoints(3.17) ' 左邊距
.RightMargin = CentimetersToPoints(3.17) ' 右邊距
End With
With secFirst.PageSetup
.PaperSize = wdPaperA4 ' 預設紙張大小
.Orientation = wdOrientPortrait ' 直向;橫向用 wdOrientLandscape
.PageWidth = CentimetersToPoints(21)
.PageHeight = CentimetersToPoints(29.7)
End With
' 在指定 Range 之後插入新區段(預設為「下一頁」區段分隔)
Dim rng As Range
Set rng = ActiveDocument.Range(0, 0) ' 文件開頭
ActiveDocument.Sections.Add Range:=rng
ActiveDocument.Sections.Last.Range.InsertAfter "文件結束!"
PageSetup,修改某區段設定不影響其他區段。wdSectionNextPage(下一頁)、wdSectionContinuous(連續)、wdSectionEvenPage(偶數頁)、wdSectionOddPage(奇數頁)。Application.ScreenUpdating = False。本文範例適用於 Word 2003 至最新 Microsoft 365 版本,VBA 物件模型相容性極高。