简体   繁体   中英

Word Macro to Add Comments to a Document Failing at Tables

I'm writing a Microsoft Word VBA macro that runs through every paragraph of a word document and adds a comment to every paragraph. That comment contains the style for that paragraph. This way a coworker can print out the document with comments and know how to style similar documents in the future.

I'm almost there, the code adds the comments to every paragraph, but dies at the first row of a table:

"This method or property is not available because the object refers to the end of a table row."

Here is the code:

Sub aa_AddStylesComment()
'
' aa_AddStylesComment Macro
' Author: Me!
'

Dim strParaStyle As String
Dim cmtNewComment As Comment

'Run through word file and delete any comments with author set to a space character (that is the author of the comments added by the script)
For J = ActiveDocument.Comments.Count To 1 Step -1
  With ActiveDocument
    If .Comments(J).Author = " " Then
      .Comments(J).Delete
    End If
  End With
Next J

'Running through every paragraph
For i = 1 To ActiveDocument.Paragraphs.Count
  With ActiveDocument

    'Get paragraph style
    strParaStyle = .Paragraphs(i).Style

    'Create a new comment and collect it - then change the author to space character
    Set cmtNewComment = Selection.Comments.Add(.Range(.Paragraphs(i).Range.Words(1).Start, (.Paragraphs(i).Range.Words(1).End - 1)), strParaStyle)
    cmtNewComment.Author = " "

  End With
Next

End Sub

You can add a check if it is a table, and then if the paragraph has cells, as follows:

    If .Paragraphs(i).Range.Tables.Count = 0 Then
        Set cmtNewComment = .Paragraphs(i).Range.Comments.Add(.Range(.Paragraphs(i).Range.Words(1).Start, (.Paragraphs(i).Range.Words(1).End - 1)), strParaStyle)
        cmtNewComment.Author = " "
    ElseIf .Paragraphs(i).Range.Cells.Count > 0 Then
        Set cmtNewComment = .Paragraphs(i).Range.Comments.Add(.Range(.Paragraphs(i).Range.Words(1).Start, (.Paragraphs(i).Range.Words(1).End - 1)), strParaStyle)
        cmtNewComment.Author = " "
    End If

Note that you don't need to use the Selection as you never change it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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