Word VBA Macros – TextBox: Add, Delete, Write
Add TextBox
This macro will add a TextBox to the active Word document:
Sub AddTextBox() ActiveDocument.Shapes.AddTextBox Orientation:=msoTextOrientationHorizontal, Left:=1, Top:=1, Width:=300, Height:=100 End Sub
Delete TextBox
This VBA macro will delete the first TextBox in the active document:
Sub DeleteTextBox() 'deletes first text box in activedoc 'not straithforward because its not easy to identify text boxes Dim oShape As Shape If ActiveDocument.Shapes.Count > 0 Then For Each oShape In ActiveDocument.Shapes If oShape.AutoShapeType = msoShapeRectangle Then 'we need to check both if oShape is of type msoShapeRectangle and its textframe contains place for writing If oShape.TextFrame.HasText = True Then oShape.Delete End If End If Next oShape End If End Sub
Write in TextBox
This Word macro uses similar methodology to write to the first TextBox in the active document:
Sub WriteInTextBox() 'writes into first text box in active doc Dim oShape As Shape If ActiveDocument.Shapes.Count > 0 Then For Each oShape In ActiveDocument.Shapes If oShape.AutoShapeType = msoShapeRectangle Then 'we need to check both if oShape is of type msoShapeRectangle and its textframe contains place for writing If oShape.TextFrame.HasText = True Then oShape.TextFrame.TextRange.InsertAfter "https://www.automateexcel.com/vba-code-library" Exit For 'we just want to write into first textbox End If End If Next oShape End If End Sub