View Single Post
 
Old 11-01-2022, 11:41 AM
AntCTAZ AntCTAZ is offline Windows 10 Office 2019
Novice
 
Join Date: Mar 2020
Posts: 2
AntCTAZ is on a distinguished road
Default Loop to Insert Comments Moving Slowly

Hello,

I have a macro that inserts a small Word comment to every paragraph (skipping tables) in a document. For a document with about 2000 paragraphs, it takes about 40 minutes, which doesn't seem right. I feel like this macro used to take half that time or less. Curious if I'm missing something dumb. Here's a simplified version of my code:

Code:
Sub AddComments()
	Application.ScreenUpdating = False
	For i = 1 To MainDoc.Paragraphs.Count
		If MainDoc.Paragraphs(i).Range.Information(wdWithInTable) = True Then
			i = MainDoc.Range(MainDoc.Range.Start, MainDoc.Paragraphs(i).Range.Tables(1).Range.End).Paragraphs.Count 'Skip over every paragraph in the table
		Else
			WordCommentString = "Comment Text"
			Call ADWSlib.AddWordRngComment(MainDoc, MainDoc.Paragraphs(i).Range, WordCommentString)
		End If
	Next
End Sub

Public Sub AddWordRngComment(WdDoc As Document, WdRng As Range, CmtText As String)
    Dim CommentErrVal As Integer
    CommentErrVal = 1
    With WdDoc
        ' sometimes Word is weird about adding a comment to the end of certain paragraphs so this adjusts the range as needed to keep trying to add it
        On Error GoTo CommentErr:
        .Comments.Add Range:=.Range(WdRng.End - CommentErrVal, WdRng.End - (CommentErrVal - 1)), text:=CmtText
    End With
Exit Sub
CommentErr:
    CommentErrVal = CommentErrVal + 1 ' if 1, 0 didnt work, try 2, 1, etc.
    If CommentErrVal > 10 Then ' after 10 tries just skip this comment
        Exit Sub
    ElseIf WdRng.End - CommentErrVal < 0 Then ' if this is less than 0 I've hit the beginning of the document - skip comment
        Exit Sub
    End If
Resume 0
End Sub
Reply With Quote