1

I have the following Word VBA code which creates a word document, puts a table on each page, and anchors a textbox to each table. On pages 2-6 the textboxes are correctly anchored and appear underneath the table. But on page 1 the table is not anchored correctly, and seems to be placed at 0, 0 on the page.

Simplified code that demonstrates the issue:

    Dim myDoc
    Set myDoc = Documents.Add
    myDoc.Select
    
    Dim i
    For i = 1 To 6
        Dim aRange
        Set aRange = ActiveDocument.Paragraphs.Last.Range
    
        Dim myTable
        Set myTable = myDoc.Tables.Add(aRange, 10, 10)
        myTable.Columns.Width = CentimetersToPoints(0.8)
        myTable.Rows.Height = CentimetersToPoints(0.8)
        
        Dim tb
        Set tb = ActiveDocument.Shapes.AddTextbox(Orientation:=msoTextOrientationHorizontal, _
            Left:=0, Top:=CentimetersToPoints(1.2), Width:=CentimetersToPoints(8), Height:=CentimetersToPoints(10), _
            Anchor:=myTable.Cell(10, 1).Range.Characters.First)
        
        Set aRange = ActiveDocument.Paragraphs.Last.Range
        aRange.InsertBreak
    
    Next i

Is there a way to get page 1 to display correctly, with the textbox appearing underneath the table?

macropod
  • 12,757
  • 2
  • 9
  • 21

1 Answers1

1

For example:

Dim myDoc As Document, i As Long
Set myDoc = Documents.Add
With myDoc
  For i = 1 To 6
    .Tables.Add Range:=.Range.Characters.Last, NumRows:=10, NumColumns:=10
    With .Tables(i)
      .Columns.Width = CentimetersToPoints(0.8)
      .Rows.Height = CentimetersToPoints(0.8)
    End With
    .Shapes.AddTextbox Orientation:=msoTextOrientationHorizontal, _
      Left:=0, Top:=CentimetersToPoints(1.2), Width:=CentimetersToPoints(8), Height:=CentimetersToPoints(10), _
      Anchor:=.Tables(i).Cell(10, 1).Range.Characters.First
  If i < 6 Then .Range.Characters.Last.InsertAfter Chr(12)
  Next i
End With
macropod
  • 12,757
  • 2
  • 9
  • 21
  • Still has the textbox on the first page aligning wrong. – YesThisIsMe Dec 26 '22 at 09:33
  • When I run the code, *every* textbox is placed in the same position below the corresponding table. What were you expecting? It could only be otherwise if you have something else in the document template that is interfering with the positioning. – macropod Dec 26 '22 at 12:08
  • Hmm, might be my version, or some other setting or something. I run this code fresh and page 1 is still a problem. Think I'll probably just write off page 1, I'm printing the finished thing automatically to pdf, so I'll just leave off page 1 when I print, and have dummy info on page 1. Thank you for your help. – YesThisIsMe Dec 26 '22 at 13:17