Search code examples
vbams-wordtextboxword-2013

How to identify a particular text box?


My VBA routine is deigned to alter text in a text box in the document's footer. Right now it is identified as follows:

Dim R1 as Word.Range
Set R1 = ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range
R1.ShapeRange(1).TextFrame.TextRange.Text = "xxxx"

However, users may modify this template and possibly add other text boxes. How do I guarantee I'm addressing the correct text box?


Solution

  • First find out what is the name of that textbox. For that you can use this code

    Sub Sample()
        Dim shp
        Dim R1 As Word.Range
    
        Set R1 = ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range
    
        For Each shp In R1.ShapeRange
            Debug.Print shp.Name
        Next shp
    End Sub
    

    Once you know the name then simply use that name

    Sub Sample()
        Dim R1 As Word.Range
    
        Set R1 = ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range
    
        R1.ShapeRange("Text Box 1").TextFrame.TextRange.Text = "xxrrrxx"
    End Sub
    

    This way even if new shapes will be added your code will always write to the correct textbox.