Excel VBA Object Variable Problem.

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.

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
 

Excel Facts

Did you know Excel offers Filter by Selection?
Add the AutoFilter icon to the Quick Access Toolbar. Select a cell containing Apple, click AutoFilter, and you will get all rows with Apple
Cross-posted here.

(please read the cross-posting rules of both forums and try to adhere to them in future ;))
 
Upvote 0

Forum statistics

Threads
1,225,669
Messages
6,186,346
Members
453,349
Latest member
neam

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top