Create several MergeField by VBA (2 Viewers)

zelarra821

Registered User.
Local time
Today, 20:07
Joined
Jan 14, 2019
Messages
849
Hi everyone.

I need help with a problem I'm having with Word.

I have a table with the field names I need to create, and I want to do it using VBA, so that it goes through the left column and generates the field as it appears in the right column, like this: {MERGEFIELD Example1}.

I've only attached an example, but I have over 800 field names and I can't do it one by one.

Please note that I'm working with Office 2021.

Thank you very much.
 

Attachments

If I understood correctly, you have one table with two columns.

First column has the names of the merge fields

Second column must have the merge fields

If so, try the following:
Code:
Sub AddFields()
    Dim t As Table
    Set t = Application.Documents(1).Tables(1)
   
    Dim i As Long
    For i = 1 To t.Rows.Count
        If i > 1 Then
            Dim r1 As Range
            Set r1 = t.Cell(i, 1).Range
           
            Dim r2 As Range
            Set r2 = t.Cell(i, 2).Range
            r2.Collapse wdCollapseStart
           
            Application.Documents(1).Fields.Add r2, wdFieldEmpty, "MERGEFIELD  " & Cleanup(r1.Text), True
        End If
    Next i
End Sub

Function Cleanup(cellText As String) As String
    Cleanup = Mid(cellText, 1, Len(cellText) - 2)
End Function
 
Hi.

It works fine for me. That's what I need.

However, there's a little problem with blank fields (attached files) when I execute to get fields value.

Screenshot_2025-05-30-09-54-49-414_com.google.android.googlequicksearchbox-edit.jpg

Is there an option to skip that window?

Thanks a lot.
 
Recuerdo que hablas español.

¿Entonces tienes campos vacíos en la columna izquierda?

Si es así, ¿Qué quieres hacer con esos campos?
1. Asignarles un nombre genérico
2. Ignorarlos y pasar al siguiente
 

Users who are viewing this thread

Back
Top Bottom