PDA

View Full Version : Solved: Using Document.Words Object in VBA



talhamoin
03-03-2011, 09:28 AM
I have written the below code to write all words from MainDocument.doc to ChangeLog.txt. It should bypass the punctuation marks. But it isn't working. I don't know why. Any idea?


Sub DictionaryCompare()
Dim docCurrent As Document
Dim LookupWord As Object

sMainDoc = "C:\Dictionary\MainDocument.doc"
Set docCurrent = Documents.Open(sMainDoc)
docCurrent.Activate

For Each LookupWord In docCurrent.Words
If LookupWord <> vbCr And LookupWord <> "." And LookupWord <> "," And LookupWord <> ";" And LookupWord <> "?" And LookupWord <> "'" Then
Open "C:\Dictionary\ChangeLog.txt" For Append As #2
Write #2, Trim(LookupWord) & "," & FontColor & "," & PartOfSpeech
Close #2
End If
Next
End Sub

Frosty
03-03-2011, 04:18 PM
Select case statement within your for loop would be much easier to read, and probably easier to troubleshoot instead of a complex If statement... for example:

Select Case LookupWord
Case vbCr, ".", ",", ";", "?", "'"
'do nothing
Case else
'write to the file
Open "C:\Dictionary\ChangeLog.txt" For Append As #2
Write #2, Trim(LookupWord) & "," & FontColor & "," & PartOfSpeech
End Select

RonMcK
03-03-2011, 06:39 PM
Frosty,

You probably want to include Close #2 after the Write and before your End Select.

Cheers,

Frosty
03-03-2011, 07:08 PM
Ron is absolutely right-- sorry, wrote that example a little quickly.

talhamoin
03-07-2011, 09:44 AM
Thanks all, especially Frosty. The case thing worked :-)