【问题标题】:Error code 462 when running macro second time第二次运行宏时出现错误代码 462
【发布时间】:2017-11-07 12:31:02
【问题描述】:

当我再次尝试运行我的代码时,我不断收到错误代码 462。该代码应该使用来自 excel 的数据创建一个 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

我试图让它忽略错误消息,说 go to endrutine 但这也不起作用。

【问题讨论】:

  • 尝试在最后关闭文档。文档的名称是如何保存的?
  • 关闭文档不起作用....代码提示用户保存,以便他们在保存时选择文档的名称。
  • 参考thisthisthis
  • 谢谢,但我已经经历过这些,谷歌在这个问题上没有多大帮助。
  • 至少应该是WordApp.Documents.Save NoPrompt:=False,尤其是当您通过 Excel 运行时。

标签: excel vba


【解决方案1】:

Documents.Save 应该是myDoc.Save。否则,您将使用不合格的对象变量,该变量会创建对 Word 对象的孤立引用。您还需要确保在重新运行代码之前关闭所有正在运行的隐藏 Winword 进程。

【讨论】:

  • 我的想法也是如此,但是当我这样做时,会出现编译错误。 “参数数量错误或属性分配无效”
  • 还有WordApp.Documents.Save ?
  • 做到了!谢谢!
  • 只是myDoc.Save,后面什么都没有。
【解决方案2】:

尝试删除这个:

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

只留下这个:

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

有人here 遇到了同样的问题。

【讨论】:

  • 现在我得到一个没有文字的错误,只有一个红色的停止标志。
  • @SIDVI - 奇怪,然后在模块顶部写Option Explicit,转到Debug>Compile,看看编译时发生了什么。然后尝试修复它,直到你能够编译为止。
  • 感谢您的尝试,我会继续努力解决的。
猜你喜欢
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2023-01-29
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
相关资源
最近更新 更多