0

我收到此错误消息:“运行时错误 5981。对象 'Documents' 的方法 'Add' 失败。” 当我使用模板创建新的 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 用户创建第二个模板来绕过错误消息。但是,为所有用户提供一个通用的共享模板会更好。

4

2 回答 2

0

更懒惰的解决方案可以是:

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

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

于 2016-09-16T14:28:35.690 回答
0

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

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

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

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

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

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

于 2016-09-16T13:57:01.207 回答