Microsoft Word Section with example VBA (Visual Basic for Applications)

Microsoft Word Section with example VBA (Visual Basic for Applications)

Section

Defines boundaries withing a Page in a Word Document. Also represents a single section in a selection, range, or document. Section is a member of the Sections collection which can be referenced by passing an index (a positive integer) or for each loop. The Sections collection includes all the sections in a Selection, Range, or Document. The following example changes the left and right page margins for the first section in the active document.

Code example

Public Sub CheckSections()
    'Bind active document
    Dim oDocument As Document
    Set oDocument = ActiveDocument
    
    'print number of sections in active document
    Debug.Print oDocument.Sections.Count
End Sub

Output

Add method

Public Sub AddSection()
    'Bind active document
    Dim oDocument As Document
    Set oDocument = ActiveDocument
    
    'Bind Range
    Dim oRange As Range
    'Set range to start of the document
    Set oRange = oDocument.Range(Start:=0, End:=0)
    'Add section
    oDocument.Sections.Add Range:=oRange
    'insert new paragraph
    oRange.InsertParagraphAfter
End Sub

Delete Section

Since there is no delete method under section object hence, we need to follow Range Delete method as given in code below:

Public Sub DeleteSection()
    'Bind active document
    Dim oDocument As Document
    Set oDocument = ActiveDocument
    
    'Declare section
    Dim oSection As Section
    'Bind section
    Set oSection = oDocument.Sections(1)
    'Select section
    oSection.Range.Select
    'delete section
    oSection.Range.Delete
End Sub

Index

Represents a positive integer number by which we can iterate particular section. In below example we will increase margin to a section:

Public Sub IncreaseMargin()
    'Bind active document
    Dim oDocument As Document
    Set oDocument = ActiveDocument
    'set left margin
    oDocument.Sections(2).PageSetup.LeftMargin = InchesToPoints(0.8)
    'set right margin
    oDocument.Sections(2).PageSetup.RightMargin = InchesToPoints(0.8)
End Sub

Please leave your comments or queries under comment section also please do subscribe to out blogs to keep your self upto date.

Leave a Reply

Your email address will not be published. Required fields are marked *