Hello
I'm trying to create a VBA code in excel that can replace the mergefields that were converted into doc variables with the data from excel.
But everytime that I run the code and open the word nothing changes. Can someone help fixing my code?
Thanks in advance
I'm trying to create a VBA code in excel that can replace the mergefields that were converted into doc variables with the data from excel.
But everytime that I run the code and open the word nothing changes. Can someone help fixing my code?
Thanks in advance
VBA Code:
Sub ReplaceDocVariables()
Dim oWord As Word.Application
Set oWord = New Word.Application
Dim oDoc As Word.Document
Set oDoc = oWord.Documents.Open("C:\Temp.print\wordTemplatee.docx")
Dim oField As Word.field
Dim xlApp As Excel.Application
Set xlApp = New Excel.Application
Dim xlWb As Excel.Workbook
Set xlWb = xlApp.Workbooks.Open("C:\Temp.print\values.xlsx")
Dim xlWs As Excel.Worksheet
Set xlWs = xlWb.Sheets(1)
Dim LastRow As Long
LastRow = xlWs.Cells(xlWs.Rows.count, "A").End(xlUp).Row
Dim i As Long
For Each oField In oDoc.Fields
If oField.Type = wdFieldDocVariable Then
For i = 1 To LastRow
If oField.Code.Text = "DOCVARIABLE " & xlWs.Cells(i, "A").Value Then
oField.Result.Text = xlWs.Cells(i, "B").Value
End If
Next i
End If
Next
oDoc.Save
oWord.Quit
xlWb.Close
xlApp.Quit
End Sub
Sub UnlinkDocVariables()
Dim oWord As Word.Application
Set oWord = New Word.Application
Dim oDoc As Word.Document
Set oDoc = oWord.Documents.Open("C:\Temp.print\wordTemplatee.docx")
Dim oField As Word.field
For Each oField In oDoc.Fields
If oField.Type = wdFieldDocVariable Then
oField.Select
oWord.Selection.Cut
End If
Next
oDoc.Save
oWord.Quit
End Sub