Search code examples
vbafooterms-word

MS Word VBA dynamic footer


I'd like to replace a label in the footer. It works but the replacment deletes the horizontal line above the footer text. How can I replace the label without deleting the horizontal line? How can I draw a line in the footer?

Private Sub Document_Open()
   Dim unit As String
   Dim footer As String
   unit = "New text"
   footer = ActiveDocument.Sections(1).Footers(wdHeaderFooterFirstPage).Range.Text
   ActiveDocument.Sections(1).Footers(wdHeaderFooterFirstPage).Range.InlineShapes.AddHorizontalLineStandard   
   footer = Replace(footer, "<<Label>>", unit)
   ActiveDocument.Sections(1).Footers(wdHeaderFooterFirstPage).Range.Text = footer
End Sub

Solution

  • There are several ways to do what you want, not all of them in VBA. What have you tried so far?

    If you want to use VBA to draw a line above the text, set the cursor where you want it and then call the following:

    With Selection.Borders(wdBorderTop)
        .LineStyle = Options.DefaultBorderLineStyle
        .LineWidth = Options.DefaultBorderLineWidth
        .Color = Options.DefaultBorderColor
    End With