用excel vba计算word中的评论数量失败



我想得到word文档中的注释数量。当word文档只有文本和注释时,我的代码就可以工作了。

但是当我在包括表的word文档上运行(excel-vba(代码时,我得到运行时错误91〃对象变量或With块变量未设置";。

我不知道是否需要这些信息:当word文档中有一个表时,表中也有对文本的注释。。。

如何更改它为每个word文档运行的代码?

提前感谢您的帮助!

现在我的代码:

Dim appWord As Word.Application
Dim document As Word.Document
ThisWorkbook.Worksheets("Tabelle4").Activate

Set appWord = CreateObject("Word.Application")

' This word document just contains text and comments and with this document there is no runtime error 91
Set document = appWord.Documents.Open( _
ThisWorkbook.Path & "Testfile_JustTextAndComments.docx")
' This word document contains tables, text and comments and with this document there arises a runtime error 91
'Set document = appWord.Documents.Open( _
'ThisWorkbook.Path & "Testfile_TableTextAndComments.docx")

' Show the amount of comments in the word document
Range("A1") = document.Comments.Count ' when I click the debug-button of the runtime error 91 this line of code is marked (with Testfile_TableTextAndComments.docx)

document.Close wdDoNotSaveChanges
appWord.Quit
Set document = Nothing
Set appWord = Nothing

由于运行时错误91对象变量或未设置块变量,建议我检查变量document是否为空(感谢所有评论者的贡献(。

' check if word document is loaded on document
If document Is Nothing Then 
   MsgBox ("document not opened")
End If 

当我运行错误91时,document是空的。

在这里将多个word文档中的注释提取到Excel中我找到了一个适合我的解决方案,这样运行时错误91就消失了。

打开word文件时,我只需要添加一些参数

Set dokument = appWord.Documents.Open(Filename:=ThisWorkbook.Path & "Testfile_TableTextAndComments.docx", AddToRecentFiles:=False, ReadOnly:=True, Visible:=False)

在这里,您可以找到一些对文档的附加提示和解释。开放式方法(Word(

现在整个代码:

Dim appWord As Word.Application
Dim document As Word.Document
ThisWorkbook.Worksheets("Tabelle4").Activate

Set appWord = CreateObject("Word.Application")

' This word document contains tables, text and comments and with the additional arguments the runtime error 91 doesn't appear anymore
Set document = appWord.Documents.Open( _
ThisWorkbook.Path & "Testfile_TableTextAndComments.docx", _
AddToRecentFiles:=False, ReadOnly:=True, Visible:=False)

' check if word document is loaded on document - but this code snippet isn't needed anymore
If document Is Nothing Then 
   MsgBox ("document not opened")
End If

' Show the amount of comments in the word document
Range("A1") = document.Comments.Count ' 

document.Close wdDoNotSaveChanges
appWord.Quit
Set document = Nothing
Set appWord = Nothing

最新更新