Microsoft Word Create Text Box using VBA (Visual Basic for Applications)

Microsoft Word Create Text Box using VBA (Visual Basic for Applications)

CreateTextbox

Creates a default size of textbox around the selection in a document. In this article we will write a code with example which will put a textbox around the selected text along with certain formatting. For example refer the below screenshot which has selection to a formatted line of text:

Code example

Sub CreateTextBoxCodeExample()
        
    'Bind selection
    Dim objSelection As Selection
    Set objSelection = Selection
    
    'Check selection type
    If objSelection.Type = wdSelectionNormal Then
        'Create text box
        objSelection.CreateTextBox
        
        'Declare shape range object to hold the shape range
        Dim oShapeRange As ShapeRange
        
		'Bind reference
        Set oShapeRange = objSelection.ShapeRange
        
        'Perform formatting
        oShapeRange.BackgroundStyle = msoBackgroundStylePreset7
        objSelection.ShapeRange(1).Line.DashStyle = msoLineDashDot
        
        'Memory cleanup
        Set oShapRange = Nothing
    End If
    
    'Memory cleanup
    Set objSelection = Nothing
End Sub

Output

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.