Search code examples
ms-wordvb6spell-checking

How to run a spell check on a string without user input?


I'm trying to run a spell check on a string using word, but I don't want to have to go through each word manually and determine the correct spelling. Is there a way to do this automatically, so that it corrects all the misspelled words on its own? Here is my code so far, this works but I have to go through each word and hit change...

If Address.Length > 0 Then
    Dim word_server As New Word.Application
    word_server.Visible = False
    Dim doc As Word.Document = word_server.Documents.Add()
    Dim rng As Word.Range

    rng = doc.Range()
    rng.Text = Address
    doc.Activate()
    doc.CheckSpelling()
    Address = doc.Range().Text
    doc.Close(SaveChanges:=False)
    word_server.Quit()
    doc = Nothing
    rCell.Value = Address
End If

Solution

  • Use the GetSpellingSuggestions function to bypass the GUI. to see if there are any spelling suggestions, and then you can set it to the first suggestion (which could be a bad idea).

    How do you want to determine what the correct spelling is? Should "spon" be spoon, span, spin, spun, or son? This code optimistically assumes that the first suggestion (if one exists) is the correct solution.

    Declare:

    Dim oError As Word.Range
    

    And then replace:

      doc.Activate()
      doc.CheckSpelling()
    

    with:

    For Each oError In rng.SpellingErrors
        If oError.GetSpellingSuggestions.Count > 0 Then
            oError.Text = oError.GetSpellingSuggestions().Item(1).Name
        Else
            'Uh oh, no suggestions, do something here.
        End If
    Next