Max_Taylor
New Member
- Joined
- Dec 9, 2012
- Messages
- 1
The code below aims to define and then load a series of variables into a new Word document being created from a template. If I define each variable "manually" it works great, but I want to define each variable with a loop as outlined. As it is, I get an error stating "Variable already exists".
Any help will be appreciated.
Thanks.
Any help will be appreciated.
Thanks.
Code:
Sub Test1()
Dim wd As Word.Application
Dim wdocSource As Word.Document
Dim i As Long
Dim varName As String
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
Set wd = CreateObject("Word.Application")
End If
On Error GoTo 0
MasterWordFile = "c:\temp\TestWordFile.dot"
PDFFileName = "c:\temp\TestPDFFile.pdf"
Set wdocSource = wd.Documents.Add(MasterWordFile)
With ActiveSheet.Range("A1")
For i = 1 To .CurrentRegion.Columns.Count
'the error is related to the line below
wdocSource.Variables.Add(.Offset(0, i - 1)).Value = .Offset(ActiveCell.Row - 1, i - 1)
Next i
Exit Sub
End With
With wdocSource
.Range.Fields.Update
.ExportAsFixedFormat PDFFileName, 17
.Close SaveChanges:=False
End With
wd.Quit
Set wdocSource = Nothing
Set wd = Nothing
End Sub