views:

282

answers:

1

I need to create a way of checking various codes in a Word document. These codes are usually a letter followed by a hyphen and 5 digits, eg M-81406. We need to check that these pre-defined codes have been typed in correctly (there is a pre-determined list of several thousand codes). We cannot use normal Word spell checking as you cannot mis-spell a number (you need at least 2 letters).

I figured I could write a macro that passes over all of the text and finds any that may be invalid. I can easily use regular expressions to check them. My question is, in a macro can I refer to a custom dictionary as the reference list of codes? As in, am I able to access the contents of a custom dictionary from a macro? I ask because this custom dictionary has already been made. I really just need a solution that is going to be able to be updated by the client easily.

Bonus points to anyone who suggests a clever way of highlighting the incorrect codes.

+1  A: 

A custom dictionary, as you probably know, is just a text file containing the words, so reference the Microsoft Scripting Runtime, and use:

Dim FSO As New FileSystemObject, FS As TextStream
Dim Code As String, Codes As New Scripting.Dictionary
Dim Paragraph As Paragraph, Word As Range

Set FS = FSO.OpenTextFile("c:\...\cust.dic")

Do Until FS.AtEndOfStream
    Code = FS.ReadLine
    If Not Codes.Exists(Code) Then Codes.Add Key:=Code, Item:=Nothing
Loop

' Use your own method for enumerating words
For Each Paragraph In ActiveDocument.Paragraphs
    Set Word = Paragraph.Range
    Word.MoveEnd WdUnits.wdCharacter, -1

    If Not Codes.Exists(Word.Text) Then
        Word.Font.Underline = wdUnderlineWavy
        Word.Font.UnderlineColor = wdColorBlue
    Else
        Word.Font.Underline = wdUnderlineNone
        Word.Font.UnderlineColor = wdColorAutomatic
    End If
Next

Not ideal, because it clobbers underlining formatting, and doesn't provide a mechanism for suggestions (although a small form built around a listbox would suffice).

The best solution would involve extending the spelling engine, unfortunately.

Mark