繁体   English   中英

Excel使用模板创建新的Word文档:运行时错误5981。对象“文档”的方法“添加”失败

[英]Excel creating new Word document using template: Run-time error 5981. Method 'Add' of object 'Documents' failed

我收到此错误消息:“运行时错误5981。对象“文档”的方法“添加”失败。” 当我使用模板创建新的Word文档时,会发生这种情况。 该代码发布在下面,并且可以正常工作,直到2016版中的第二个用户开始使用它为止。 它适用于所有使用旧版Word模板的2013年用户。 进入下面的Set wdDoc = wdApp ...行时,将显示错误。

Public wdDoc As Word.Document
QuoteDirectory = "R:\PartsQuotes\"
QuoteTemplate = "QuoteTemplate.dot" 'template used for 2013 users
If Application.Version = "16.0" Then QuoteTemplate = QuoteTemplate2016.dotx"
Set wdApp = CreateObject("Word.Application") 'Create an instance of word
Set wdDoc = wdApp.Documents.Add(QuoteDirectory & QuoteTemplate) 'Open word file
wdApp.Visible = True

创建Word文档后,我需要做很多其他事情,这就是为什么我需要将其创建为Word.Document的原因。 我可以通过为第二个2016年用户创建第二个模板来解决该错误消息。 但是,为所有用户提供一个通用的共享模板会更好。

我自己的Excel应用程序将打开Word模板。

调用此语句时会引发错误5981:

Set oTemplate = moWordApp.Documents.Add(template:=sTemplate, Visible:=True)

打开现有的Word文档时,也可能触发该错误:

moWordApp.Documents.Open(FileName:=...

在我的情况下,错误5981的原因是Word模板不是受信任的文档。 手动打开Word模板时,已在受保护的视图中打开它。 通过VBA自动打开模板时,这显然会导致错误5981。

懒惰的解决方案可以是:

Dim wdDoc As Word.Document
Set wdDoc = GetObject("R:\PartsQuotes\QuoteTemplate.dot", "Word.Application") 
wdDoc.Application.Visible = True

这将基于当前Word实例中的模板打开一个新文档,或者如果没有打开,将打开新的Word应用程序。

或先尝试.dotx模板:

Dim wdDoc As Word.Document
On Error Resume Next
Set wdDoc = GetObject("R:\PartsQuotes\QuoteTemplate2016.dotx", "Word.Application") 
If Err.Number <> 0 Then 
    Set wdDoc = GetObject("R:\PartsQuotes\QuoteTemplate.dot", "Word.Application") 
End If
If not wdDoc Is Nothing Then wdDoc.Application.Visible = True
On Error GoTo 0 ' optional to reset the error handler

另请注意,可以从Office 2007开始打开* x文件,其中.Application.Version = "12.0"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM