Visual Basic for Applications/Generate Random Dictionary Words

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Summary[edit | edit source]

This VBA code module works only in MS Word. It generates a pseudo random list of dictionary words, listing them in the immediate window of the VBA editor.

The VBA Code[edit | edit source]

  • Copy the code listing into a standard VBA module in MS Word and save the file as a docm type. Set the user options in the top section and run the procedure to produce the list.
  • The variable Num sets the number of words as output, and the variable TypoLen should be set to the approximate length of the sought-after words.
  • There is no ready-made collection of English words called a Dictionary in MS Word; the term is used for sets of user-constructed word lists. To access a list of English words, an indirect method needs to be used. A random word is first generated equal in length to TypoLen. The spell checker then fails to recognize the word so generates suggestions, this time as a proper collection. Provided that there is at least one such suggestion in the spell check collection, a random choice is made from among them for the output list. The loop continues until the chosen number of words has been produced.

The Code Module[edit | edit source]

Sub GetNRandomWords()
    'Prints N randomly selected words
    'in the Immediate Window
    'Works in MS WORD only
    
    Dim Sugg As SpellingSuggestions
    Dim TypoLen As Long, n As Long
    Dim sMakeWord As String, nR As Long
    Dim Num As Long, p As Long
    
    'set user options
    TypoLen = 7 'trial text length
    Num = 10    'number of samples
    
    Randomize
    Do
        p = p + 1
        Do
            DoEvents
            sMakeWord = ""
            'make a misspelled word of length TypoLen
            For n = 1 To TypoLen
                'concatenate random charas
                sMakeWord = sMakeWord & Chr(Int(26 * Rnd + Asc("a")))
            Next n
            
            'get resulting spelling suggestions collection
            Set Sugg = GetSpellingSuggestions(sMakeWord)
            
            'random select a suggestion
            If Sugg.Count >= 1 Then 'assuming there is at least one
                'random select one suggestion
                nR = Int((Sugg.Count - 1 + 1) * Rnd + 1)
                Debug.Print Sugg(nR) 'OUTPUT
                'MsgBox Sugg(nR)
            End If
        Loop Until Sugg.Count >= 1
    Loop Until p >= Num

End Sub

See Also[edit | edit source]

External Links[edit | edit source]