'Add comments based on variable
My goal is to search for terms or words in documents against a Master table that contains the terms that should not be used in documents as well as a suggestion for the writer. I have a Master table I call the Matrix that contains two columns: Term, Suggestion. For example:
Term= ubiquitous Suggestion= "Don't use ubiquitous, instead use everywhere".
I need help to find a way to add Suggestions as comments every time I find a word that is in the Master table.
Below my code. I omitted the loops and user input because the issue is: How to add comments that point to the word that was found in the document being validated.
Sub AddSideCommentsToWordDocument()
Dim MatrixDoc As Word.Document 'This is the master table with terms
Dim MatrixPath As String 'File path to master table
Dim DocToValidate As Word.Document 'This is the file in question to validate
Dim DocumentPath As String 'This is the file path to the file in question
Dim Suggestion As String 'Variable to store suggested comment
Dim WordToCheck As String 'Variable to store the word to validate against Master table term
DocumentPath = "C:\Folder\FileInQuestion.docx" 'These paths will come from user input
MatrixPath = "C:\Folder\Master Terms Matrix.docx"
Set MatrixDoc = Documents.Open(MatrixPath) 'Open Master Table
Set DocToValidate = Documents.Open(DocumentPath) 'Open doc in question
'Get first term from Master Table into a variable
TermFromMatrix = MatrixDoc.Tables(1).Rows(1).Cells(ColumnWithTerm).range.Text
'Get first suggested comment from Master Table into a variable
Suggestion = MatrixDoc.Tables(1).Rows(1).Cells(ColumnWithSuggestion).range.Text
'Get first word from document to validate into a variable
WordToCheck = DocToValidate.Words(i).Text
'Compare first term from Master Table vs. First word from document to validate
If TermFromMatrix = WordToCheck Then
DocToValidate.Comments.Add Text:=Suggestion 'I get the following error: Argument not optional
End If
Close
End Sub
Solution 1:[1]
You are missing the Range argument which tells Word where to attach the comment:
Sub Tester()
Dim i As Long
With ActiveDocument
For i = 1 To .Range.Words.Count
If .Words(i).Text = "theme" Then
.Comments.Add Range:=.Words(i), Text:="not theme"
End If
Next i
End With
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
