Search code examples
excelvbaruntime-error

Excel VBA 438 error when using thisworkbook and word application in same script


I'm testing out a method for a bigger project and am running into 438 errors for this script. If I grab the worksheet first, the error comes from calling word.application, if I grab the word doc stuff first, the 438 throws when I grab the worksheet. I cannot find any viable solutions for this, though I did try early binding, and have begun copying the document first so that it's always working in a fresh Word doc to avoid other conflicts. What else could be the issue here?

Option Explicit

Sub Merge()
    Dim WordDoc As Object, N As Variant, i As Integer, j As Integer
    'i = Range("C2").Value  'pulls length of list from an excel function located in cell C2 =COUNTIF(B4:B5005,"*")
    Dim wordApp As Word.Application
    Dim source As String
    Dim destination As String
    Dim xlobj As Object
    Set xlobj = CreateObject("Scripting.FileSystemObject")
    source = "C:\...\MERGE TEMPLATE - CONSTRUCTION LOAN AGREEMENT.docx"
    destination = "C:\...\WORKING - CONSTRUCTION LOAN AGREEMENT.docx"
    xlobj.CopyFile source, destination, True
    Set xlobj = Nothing
    Set wordApp = CreateObject(Class:="Word.Application")
    wordApp.Options.SaveInterval = 0
    Set WordDoc = wordApp.Documents.Open("C:\...\WORKING - CONSTRUCTION LOAN AGREEMENT.docx")
    WordDoc.Visible = True
    Dim dataws As Worksheet
    Set dataws = ThisWorkbook.Worksheets("Merge Fields")
    N = dataws.Range("a1:b1").Value 'test row
    Print (N)
   'For j = 1 To i
    With wordApp
        With WordDoc.Content.Find
            .Text = N(1, 1)
            .Replacement.Text = N(1, 2)
            .Wrap = wdFindContinue
            .MatchWholeWord = True
            .Execute Replace:=wdReplaceAll
      End With
    End With
    'Next j
    wordApp.ActiveDocument.Save
    wordApp.ActiveDocument.Close
    wordApp.Quit

    Set wordApp = Nothing
    Set WordDoc = Nothing
End Sub

Solution

  • WordDoc.Visible = True
    

    should be

    wordApp.Visble = True
    

    Document doesn't have a Visible property.