Giacomo Moleri
Giacomo Moleri

Reputation: 11

Macro in word to add text box with file path

I'm totally new to this. I want to create a macro that add to my document the file path (at the time when the macro runs) into a text box that goes at the end of the document. I use Word 2016 for Mac.

I've found code on other threads that helped me to understand how to create the text box and work on its position in the document but I'm not able to add the file path code.

This is what I came up with so far:

    Sub percorsofile2()
    Dim Box As Shape
    Set Box = ActiveDocument.Shapes.AddTextbox( _
    Orientation:=msoTextOrientationHorizontal, _
    Left:=50, Top:=50, Width:=100, Height:=15)
    Box.TextFrame.TextRange: Selection.Fields.Add Range:=Selection.Range, 
    Type:=wdFieldEmpty, Text:="FILENAME \p "

Upvotes: 1

Views: 221

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25673

You're very close! Just one little change...

The Selection is not in the TextBox, which is why the field code is not getting inserted in the right place. While you could first select the TextBox range, it's usually better to work directly with a Range object, rather than a selection.

My sample code declares a Range object, then sets it to the Box.TextFrame.TextRange. The field code can then be inserted at this position.

Sub percorsofile2()
    Dim Box As Shape
    Dim rng As Word.Range

    Set Box = ActiveDocument.shapes.AddTextbox( _
              Orientation:=msoTextOrientationHorizontal, _
              Left:=50, Top:=50, width:=100, height:=15)
    Set rng = Box.TextFrame.TextRange
    rng.Fields.Add Range:=rng, Type:=wdFieldEmpty, Text:="FILENAME \p " 
End Sub

Upvotes: 1

Related Questions