Home » excel » excel – Error code 462 when running macro second time

excel – Error code 462 when running macro second time

Posted by: admin April 23, 2020 Leave a comment

Questions:

i keep getting an error code 462, when i try to run my code a second time. The code is supposed to create a word document with data from excel, and then prompt user to save that document. It is the save part of the code, that gives the error.

Here is the code:

Sub ExportToWord()

Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Dim SrcePath As String

    Range("G3:J29").Copy

    'Create an Instance of MS Word
  On Error Resume Next

    'Is MS Word already opened?
      Set WordApp = GetObject(class:="Word.Application")

    'Clear the error between errors
      Err.Clear

    'If MS Word is not already open then open MS Word
      If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")

    'Handle if the Word Application is not found
      If Err.Number = 429 Then
        MsgBox "Microsoft Word could not be found, aborting."
        GoTo EndRoutine
      End If

  On Error GoTo 0

    'Make MS Word Visible and Active
    WordApp.Visible = True
    WordApp.Activate

    'Create a New Document
    Set myDoc = WordApp.Documents.Add

    'Paste Table into MS Word
    myDoc.Paragraphs(1).Range.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

    'Autofit Table so it fits inside Word Document
    Set WordTable = myDoc.Tables(1)
    WordTable.AutoFitBehavior (wdAutoFitWindow)

    'Insert Header logo
    SrcePath = "C:\Users\SIDVI\Pictures\logo.gif"

    myDoc.Sections.Item(1).Headers(wdHeaderFooterPrimary) _
        .Range.InlineShapes.AddPicture (SrcePath)

    'Prompts users to save document
    Documents.Save NoPrompt:=False

    If Err.Number = 462 Then
        GoTo EndRoutine
    End If

EndRoutine:
'Optimize Code
  Application.ScreenUpdating = True
  Application.EnableEvents = True

'Clear The Clipboard
  Application.CutCopyMode = False

End Sub

I have tried to get it go ignore the error message, by saying go to endrutine but this does not work either.

How to&Answers:

Documents.Save should be myDoc.Save. Otherwise you are using an unqualified object variable which creates an orphaned reference to the Word object. You’ll also need to make sure that you close any hidden Winword processes that are running before re-running the code.

Answer:

Try deleting this:

'Is MS Word already opened?
  Set WordApp = GetObject(class:="Word.Application")

And leave only this:

  If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")

Someone here had the same problem.