0
votes

I'm trying to use Powershell to remove all sentences flagged by the Microsoft Word Grammar Checker. I got pretty far looking at the Office Word 2010 Word Object Model. I was able to find the next grammatical incorrect sentence in a document, and was able to delete it. My only problem now is to loop through a document and to delete all of sentences flagged by Microsoft Word Grammar Checker. Here's what I have so far.


    cd c:\testruns\
       $docPath = "" + $(Get-Location) + "\Grammar\document.docx"
       $Word = New-Object -ComObject Word.Application
       $Word.Visible = $True
       $doc = $Word.documents.open($docPath)
       $docSelection = $Word.selection

       # Word Method Constants
       $wdGoToSpellingError = 13
       $wdGoToGrammaticalError = 14
       $wdGoToFirst = 1
       $wdGoToLast = -1
       $wdGoToNext = 2

       while (!$AnymoreGrammar) {
           [void]$docSelection.GoTo($wdGoToGrammaticalError, $wdGoToNext).delete()
       }

Of course the variable $AnymoreGrammar is just pseudocode for a boolean variable that I want to find. I need a valid boolean test in the while loop that checks to see if the document has anymore grammatical errors. If I don't, than the $wdGoToNext will keep going even if there's no grammatical errors. It deletes the first sentence's letter if it can't find a sentence that's flagged with a grammatical error. Any help? I'm using this as a reference.

(http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.wdgotoitem.aspx)

2

2 Answers

0
votes

The problem is that your $docSelection is not updated. What you do is delete a sentence and then delete the very same sentence from the very same selection again and again and again. You need to update $docSelection after each deletion, like this:

       while (!$AnymoreGrammar) {      
       $docSelection.GoTo($wdGoToGrammaticalError, $wdGoToNext).delete()
       $docSelection = $Word.selection
   }

It deleted everything from the doc for me, but at least it's looping now

0
votes

Ended up solving it a bit ago. Found a ProofreadingError object that contains a property called Count that returns the number of GrammaticalErrors. (msdn.microsoft.com/en-us/library/aa213190(v=office.11).aspx)

So I set the While Loop test to

$errorCount = $doc.GrammaticalErrors.Count

while ($errorCount -ne 0)