Search code examples
vbams-wordtextbox

VBA in Word always sets textbox indents to same wrong value


I'm trying to create a textbox in Word using VBA, but Word consistently createst the textbox with left and right indents about 5 inches apart, indented about 1 inch from each side. I've tried everything I can think of - setting the indents myself (failed), clearing all paragraph formatting first (failed), clearing all tab stops (failed), and resetting the left/right indents a second time at the end of my code.

I can see the tab stops when I click in the created text box, and if I manually move them the text inside responds appropriately. Does anyone know what am I doing wrong (or not doing)? The ShapeTboxCreate subroutine just creates teh text box normally, but converts the parameters (in inches) to points before passing them to the .Shapes.AddShape(msoTextBox,...) function.

Thank you.

   Set tbox = ShapeTboxCreate(0.5, 0.37, 7.5, 0.75)
   tbox.name = "Header Title Box"
   selection.ClearParagraphAllFormatting
   selection.Collapse wdCollapseStart
   tbox.TextFrame.TextRange.ParagraphFormat.TabStops.ClearAll
   tbox.TextFrame.TextRange.ParagraphFormat.LeftIndent = 0
   tbox.TextFrame.TextRange.ParagraphFormat.RightIndent = 0
   tbox.TextFrame.TextRange.Text = "My Text Here"

Here is the subroutine. It converts the parameters (in inches) to points and creates the rectangle.

Function ShapeRectCreate(left As Single, top As Single, width As Single, _
   height As Single) As Shape
Dim shp As Shape
Set shp = ActiveDocument.shapes.AddShape(msoShapeRectangle, 0, 0, _
      InchesToPoints(width), InchesToPoints(height))
shp.RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
shp.RelativeVerticalPosition = wdRelativeVerticalPositionPage
shp.left = InchesToPoints(left)
shp.top = InchesToPoints(top)
Set ShapeRectCreate = shp
End Function

Solution

  • The problem was in the code that created the text box. This code looks like it should work, but it created an ellipse with a smiley face in it, embedded in the text box. The tabs were set by the smiley face character. Totally weird, I know.

    ActiveDocument.Shapes.AddShape(msoTextBox,...)
    

    When I replaced the code above with this code, everything worked as expected:

    ActiveDocument.Shapes.AddTextbox(msoTextOrientationHorizontal,...)
    

    Maybe this might help someone someday.