Search code examples
vbams-wordinsertrangetext-formatting

Add mail merge field with VBA and set specific font settings


The purpose of this VBA is to find the text "Something" in the document, insert a space after it, add a mail merge field named "address" and then format the inserted field with specific font settings. The adding part works fine but the text does not get formatted.

Sub AddMailMergeField()
    Dim rng As Range
    
    ' Set the range after "Something" text
    Set rng = ActiveDocument.Range
    rng.Find.Text = "Something"
    rng.Find.Execute
    
    ' Insert a space 
    rng.Collapse Direction:=wdCollapseEnd
    rng.InsertAfter " "
    
    ' Insert the mail merge field "address"
    ActiveDocument.MailMerge.Fields.Add rng, "address"
    
    ' Format the inserted field
    With rng
        .Font.Name = "Arial"
        .Font.Size = 30
        .Font.ColorIndex = wdRed
    End With
End Sub

Solution

  • Modify your code with this:

    Instead With rng place this

        rng.Expand wdWord
        rng.Select
        With Selection