應用程式 VBA/生成隨機字典詞
外觀
< 應用程式 VBA
此 VBA 程式碼模組僅在 MS Word 中有效。它會生成一個偽隨機字典詞列表,並在 VBA 編輯器的立即視窗中列出它們。
- 將程式碼清單複製到 MS Word 中的標準 VBA 模組中,並將檔案儲存為 docm 型別。在頂部的部分設定使用者選項,並執行該過程以生成列表。
- 變數 Num 設定輸出詞的數量,變數 TypoLen 應設定為所需詞的近似長度。
- MS Word 中沒有名為 Dictionary 的現成英語詞語集合;此術語用於指代使用者建立的詞語列表集。要訪問英語詞語列表,需要使用間接方法。首先生成一個與 TypoLen 長度相同的隨機詞。然後拼寫檢查器無法識別該詞,因此會生成建議,這次作為正確的集合。假設拼寫檢查集合中至少有一個這樣的建議,則從其中隨機選擇一個用於輸出列表。迴圈持續到生成選定的詞語數量為止。
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