none
Adding textbox to every section in word does not work when the second section is unlinked to previous RRS feed

  • Question

  • Hi,

    I am using this code to insert textbox to every page in word :

    foreach (Section section in Document.Sections)
    	{
    		var header = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
    		var shapw = header.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, textBox.Left, textBox.Top, textBox.Width, textBox.Height);
    	}

    However, if i create a document with 2 pages and adding a section break in the second page and unlink it from previous page, the textbox is added twice to the first page (one above the other), and there is no textbox in the second page.

    Does somone have a solution for that case, or its a Word bug?

    Thanks!

    Friday, May 20, 2016 7:05 AM

Answers

  • You should be specifying where to add the textbox and only inserting one if the Section isn't linked to the previous one. The following macro shows how you might go about that:

    Sub Demo()
    Dim Sctn As Section
    For Each Sctn In ActiveDocument.Sections
      With Sctn.Headers(wdHeaderFooterPrimary)
        If .LinkToPrevious = False Then
          .Shapes.AddTextbox msoTextOrientationHorizontal, 10, 10, 10, 10, .Range.Characters.Last
        End If
      End With
    Next
    End Sub


    Cheers
    Paul Edstein
    [MS MVP - Word]

    • Marked as answer by shenhavba Friday, May 20, 2016 12:42 PM
    Friday, May 20, 2016 9:17 AM

All replies

  • You should be specifying where to add the textbox and only inserting one if the Section isn't linked to the previous one. The following macro shows how you might go about that:

    Sub Demo()
    Dim Sctn As Section
    For Each Sctn In ActiveDocument.Sections
      With Sctn.Headers(wdHeaderFooterPrimary)
        If .LinkToPrevious = False Then
          .Shapes.AddTextbox msoTextOrientationHorizontal, 10, 10, 10, 10, .Range.Characters.Last
        End If
      End With
    Next
    End Sub


    Cheers
    Paul Edstein
    [MS MVP - Word]

    • Marked as answer by shenhavba Friday, May 20, 2016 12:42 PM
    Friday, May 20, 2016 9:17 AM
  • Thank you!

    When i added the header.Range as Anchor parameter to AddTextbox function it solved the problem

    Friday, May 20, 2016 12:42 PM
  • Hi shenhavba,

    I am glad to hear that you have resolved your issue, and thanks for your sharing your solution, that will help other community members when they have this same issue.

    Thanks again.
    Monday, May 23, 2016 5:36 AM