Microsoft Word Frame Object with VBA (Visual Basic for Applications)

Microsoft Word Frame Object with VBA (Visual Basic for Applications)

Frame

Microsoft Document object exposes Frame object which creates surrounded border or frame to the selected range. In this example we will select a range and add a frame around it.

Code example

Public Sub FrameCodeExample()
    'Declare object to hold document
    Dim oDoc As Document
    
    'Bind active document reference
    Set oDoc = ActiveDocument
    
    'Range object
    Dim oRange As Range
    Set oRange = Selection.Range

    
    oDoc.Frames.Add oRange
    
    'cleanup
    If Not oRange Is Nothing Then
        Set oRange = Nothing
    End If
    If Not oDoc Is Nothing Then
        Set oDoc = Nothing
    End If
End Sub

Output

Frames collection

Refers to collection of all available frames in a document which can be iterated using index. Border property helps changing border of frame:

Code example

Public Sub FramesExample()
    'Declare object to hold document
    Dim oDoc As Document
    
    'Bind active document reference
    Set oDoc = ActiveDocument
    
    'Total available frames
    oDoc.Frames.Count
    
    Dim oFrame As Frame
    'Get range of each frame
    For Each oFrame In oDoc.Frames
        Debug.Print oFrame.Range.Text
    Next oFrame
    
    'Delete specific frame
    oDoc.Frames(1).Delete
    
    'cleanup
    If Not oFrame Is Nothing Then
        Set oFrame = Nothing
    End If
    If Not oDoc Is Nothing Then
        Set oDoc = Nothing
    End If
End Sub

Next >> Footnote in Microsoft Word with code example

Leave a Reply

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