第二次运行macros时出现错误代码462

我不断收到错误代码462,当我尝试第二次运行我的代码。 代码应该用excel中的数据创build一个word文档,然后提示用户保存该文档。 这是代码的保存部分,给出了错误。

这里是代码:

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 

我试图让它去忽略错误信息,说去endrutine,但这也不pipe用。

Documents.Save应该是myDoc.Save 。 否则,您正在使用创build对Word对象的孤立引用的非限定对象variables。 您还需要确保在重新运行代码之前closures正在运行的任何隐藏的Winword进程。

尝试删除这个:

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

只留下这个:

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

这里有人有同样的问题。