萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Word 教學 >> Word 使用技巧

Word VBA 程式設計:Sections/Section 物件完整操作指南

在 Word VBA 開發中,Sections 集合與 Section 物件是控制文件版面配置(頁邊距、紙張大小、頁眉頁腳等)的核心。本文彙整常用屬性、方法與程式碼範例,供具備 VBA 基礎的開發者快速查閱。

核心物件結構

  • ActiveDocument.Sections:取得目前文件的所有區段集合。
  • Section:代表單一區段,透過索引(1-based)或 First/Last 屬性存取。
  • PageSetup:區段的頁面設定物件,控制實際列印版面。

常用屬性與程式碼範例

1. 存取特定區段

' 第一區段
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

2. 讀寫頁邊距(單位:Points,1 cm ≈ 28.35 pt)

With secFirst.PageSetup
    .TopMargin = CentimetersToPoints(2.54)    ' 上邊距 2.54 cm
    .BottomMargin = CentimetersToPoints(2.54) ' 下邊距
    .LeftMargin = CentimetersToPoints(3.17)   ' 左邊距
    .RightMargin = CentimetersToPoints(3.17)  ' 右邊距
End With

3. 紙張尺寸與方向

With secFirst.PageSetup
    .PaperSize = wdPaperA4          ' 預設紙張大小
    .Orientation = wdOrientPortrait ' 直向;橫向用 wdOrientLandscape
    .PageWidth = CentimetersToPoints(21)
    .PageHeight = CentimetersToPoints(29.7)
End With

4. 新增區段

' 在指定 Range 之後插入新區段(預設為「下一頁」區段分隔)
Dim rng As Range
Set rng = ActiveDocument.Range(0, 0) ' 文件開頭
ActiveDocument.Sections.Add Range:=rng

5. 在最後一區段末尾插入文字

ActiveDocument.Sections.Last.Range.InsertAfter "文件結束!"

實務應用提醒

  • 區段獨立性:每個區段擁有獨立的 PageSetup,修改某區段設定不影響其他區段。
  • 區段分隔類型:新增區段時可指定 wdSectionNextPage(下一頁)、wdSectionContinuous(連續)、wdSectionEvenPage(偶數頁)、wdSectionOddPage(奇數頁)。
  • 效能考量:大量迴圈處理區段時,建議先關閉螢幕更新:Application.ScreenUpdating = False。

適用版本

本文範例適用於 Word 2003 至最新 Microsoft 365 版本,VBA 物件模型相容性極高。

copyright © 萬盛學電腦網 all rights reserved