# VBForums CodeBank > CodeBank - Visual Basic 6 and earlier >  Advanced VB/Office Guru SpellChecker

## RobDog888

*Gangsta Yoda* 

*Description:*
I wrote this to demonstrate how to take full advantage of MS Word's built in Spelling and Grammer checker. There 
are a few other code examples that show how to do spell checking with Word but they are all using the same technique that 
seems to have a few issues like showing the spell dialog behind your app, messing up the line breaks so you need to 
apply a code fix to restore them, flashing window, etc.

What makes my spell checker different is that I use the actual spell/grammer checking dialog window and not invoking it by 
coding the usual - "Document.CheckSpelling" which seems to cause the mentioned issues.

Since I use the dialog window I preset the type of spelling I wish to perform. Now you can make it dynamic by having a 
spell options form in your app to allow the user to preset it to either Ignore words in UPPERCASE, urls, mixed words and 
numbers, check grammer, and whether to show spelling suggestions, etc.

*Requirements:*
Microsoft Word
Versions 8.0 - 11.0 (97 - 2003)



















VB Code:
'In a module (Module1.bas)
Option Explicit
'Copyright © 2005 by RobDog888 (VB/Office Guru). All Rights reserved.
'
'Distribution: You can freely use this code in your own
'              applications provided that this copyright
'              is left unchanged, but you may not reproduce
'              or publish this code on any web site, online
'              service, or distribute as source on any
'              media without express permission.
'
'Early binding:
'Add a reference to MS Word xx.0 Object Library
'Modifications: none.
 'Late binding:
'No references needed to any version of Word
'Modifications: Change object vars definitions (moApp & oDoc) to Object
'Change constants to their numeric equilivalents.
 'Requirements:
'MS Word version 97 (8.0) - 2003 (11.0)
 Public moApp As Word.Application
Private mbKillMe As Boolean
 Public Property Get KillMe() As Boolean
    InitializeMe
    KillMe = mbKillMe
End Property
 Public Property Let KillMe(Value As Boolean)
    mbKillMe = Value
End Property
 Public Sub InitializeMe()
    On Error Resume Next
    '<INITIALIZE WORD>
    Set moApp = GetObject(, "Word.Application")
    If TypeName(moApp) <> "Nothing" Then
        Set moApp = GetObject(, "Word.Application")
    Else
        Set moApp = CreateObject("Word.Application")
        mbKillMe = True
    End If
End Sub
 Public Function SpellMe(ByVal msSpell As String) As String
     On Error GoTo No_Bugs
     Dim oDoc As Word.Document
    Dim iWSE As Integer
    Dim iWGE As Integer
    Dim sReplace As String
    Dim lResp As Long
     If msSpell = vbNullString Then Exit Function
    InitializeMe
    Select Case moApp.Version
        Case "9.0", "10.0", "11.0"
            Set oDoc = moApp.Documents.Add(, , 1, True)
        Case "8.0"
            Set oDoc = moApp.Documents.Add
        Case Else
            MsgBox "Unsupported Version of Word.", vbOKOnly + vbExclamation, "VB/Office Guru SpellChecker"
            Exit Function
    End Select
    Screen.MousePointer = vbHourglass
    App.OleRequestPendingTimeout = 999999
    oDoc.Words.First.InsertBefore msSpell
    iWSE = oDoc.SpellingErrors.Count
    iWGE = oDoc.GrammaticalErrors.Count
    '<CHECK SPELLING AND GRAMMER DIALOG BOX>
    If iWSE > 0 Or iWGE > 0 Then
        '<HIDE MAIN WORD WINDOW>
        moApp.Visible = False
        If (moApp.WindowState = wdWindowStateNormal) Or (moApp.WindowState = wdWindowStateMaximize) Then
            moApp.WindowState = wdWindowStateMinimize
        Else
            moApp.WindowState = wdWindowStateMinimize
        End If
        '</HIDE MAIN WORD WINDOW>
        '<PREP CHECK SPELLING OPTIONS DIALOG BOX (MODIFY TO YOUR PREFERENCES)>
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.Options.CheckGrammarWithSpelling = True
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.Options.SuggestSpellingCorrections = True
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.Options.IgnoreUppercase = True
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.Options.IgnoreInternetAndFileAddresses = True
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.Options.IgnoreMixedDigits = False
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.Options.ShowReadabilityStatistics = False
        '</PREP CHECK SPELLING OPTIONS DIALOG BOX (MODIFY TO YOUR PREFERENCES)>
        '<DO ACTUAL SPELL CHECKING>
        moApp.Visible = True
        moApp.Activate
        lResp = moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Display
        '</DO ACTUAL SPELL CHECKING>
        If lResp < 0 Then
            moApp.Visible = True
            MsgBox "Corrections Being Updated!", vbOKOnly + vbInformation, App.ProductName
            Clipboard.Clear
            oDoc.Select
            oDoc.Range.Copy
            sReplace = Clipboard.GetText(1)
            '<FIX FOR POSSIBLE EXTRA LINE BREAK AT END OF TEXT>
            If (InStrRev(sReplace, Chr(13) & Chr(10))) = (Len(sReplace) - 1) Then
                sReplace = Mid$(sReplace, 1, Len(sReplace) - 2)
            End If
            '</FIX FOR POSSIBLE EXTRA LINE BREAK AT END OF TEXT>
            SpellMe = sReplace
        ElseIf lResp = 0 Then
            MsgBox "Spelling Corrections Have Been Canceled!", vbOKOnly + vbCritical, "VB/Office Guru SpellChecker"
            SpellMe = msSpell
        End If
    Else
        MsgBox "No Spelling Errors Found" & vbNewLine & "Or No Suggestions Available!", vbOKOnly + vbInformation, _
        "VB/Office Guru SpellChecker"
        SpellMe = msSpell
    End If
    '</CHECK SPELLING AND GRAMMER DIALOG BOX>
    oDoc.Close False
    Set oDoc = Nothing
    '<HIDE WORD IF THERE ARE NO OTHER INSTANCES>
    If KillMe = True Then
        moApp.Visible = False
    End If
    '</HIDE WORD IF THERE ARE NO OTHER INSTANCES>
    Screen.MousePointer = vbNormal
    Exit Function
No_Bugs:
    If Err.Number = "91" Then
        Resume Next
    ElseIf Err.Number = "462" Then
        MsgBox "Spell Checking Is Temporary Un-Available!" & vbNewLine & "Try Again After Program Re-Start.", _
        vbOKOnly + vbInformation, "ActiveX Server Not Responding"
        Screen.MousePointer = vbNormal
    ElseIf Err.Number = 429 Then
        Set moApp = Nothing
        Resume Next
    Else
        MsgBox Err.Number & " " & Err.Description, vbOKOnly + vbInformation, App.ProductName
        Screen.MousePointer = vbNormal
    End If
End Function
 '*********************************************************
 'Example usage:
'Behind a form (Form1)
'
'Add a single or multi-line textbox to your form
'Add a command button (Command1) to invoke the spell checking.
Option Explicit
 Private Sub Command1_Click()
    '<SPELL CHECK>
    Text1.Text = SpellMe(Text1.Text)
End Sub
 Private Sub Form_Load()
    '<CALL THE SPELLME INITIALIZATION PROCEDURE BEFORE ANY USE>
    InitializeMe
End Sub
 Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
    If KillMe = True Then
        moApp.Quit False
    End If
    Set moApp = Nothing
End Sub

----------


## eyeRmonkey

Thanks for the code RD!  :Big Grin: 

I seem to be having a problem with Word not closing when the spell check is done. the document is closing but word stays open with a blank MDI type window.

Also, is there a way to make word not show in the taskbar when this is all happening? Its not a big deal, but if there is a simple solution, that would be nice.

Thanks.

----------


## RobDog888

Can you post your code so I can see how its being implemented? Not the module code but your form code.  :Smilie: 

I can probably come up with a way to hide word in the taskbar. Give me some time to test an idea.

 :Thumb:

----------


## eyeRmonkey

I really can't narrow it down to a certain part of the code so I am posting it all in an attachment.

----------


## RobDog888

EM, I updated my example with the fix for a possible extra line break that may or may not be added to the end of the replacement text.

I will look at your code later today. I am leaving for an appointment.

----------


## RobDog888

Ok, I made a few updates to the code in my original post. It will now hide the blank Word app between spell check runs if no other 
instance of Word is running. If there are then .Close'ing the document will remove it from the taskbar automatically. 

There is no easy way to remove Word from the taskbar when it is checking spelling though.

----------


## dglienna

Hmmm.  It corrected ttest, but it left S instead of A.  Then it capitalized the first word in the sentence.

Before




> this is a test, this is only s ttest


After




> This is a test, this is only s test


I didn't think Word did that.  I'll have t try it.

EDIT:  Word does the same thing.  Odd.

Great Job.  I like Grammar Check!

----------


## RobDog888

How weird! I tested it and it doesnt pickup the s. I tested it also in Word and same results. Hmm...

----------


## RobDog888

This also doesnt get detected in MS Word.



> test s is not a workin.





> Test s is not a working.


I think Bill needs some Grammer lessions.  :Big Grin:

----------


## dglienna

LOL.  That was an actual typo, but after proof-reading it to make sure the misspelled word ttest was in there, I decided to leave it.  Go Figure!

Have to spread it around some. Got you for a 'Net thread the other day for the Line Numbers.  I wondered how you would find line 697, but wasn't about to count them!

Thanks.

----------


## RobDog888

:LOL:  I was doing a spell check on my verbiage on the original post and I came up with some spelling errors! 

Just in case anyone is wondering about what is the ShowReadabilityStatistics then this is what it looks like after the checking is complete.


Ps, Thanks Dave, I'm glad its starting to get some good feedback.  :Big Grin:  

*Gangsta Yoda*

----------


## MartinLiss

Can this be converted to VBScript? I ask because I use the "old" method in a script file to spellcheck posts.

----------


## RobDog888

I think most of it can be writtne in VB Script but I dont really know it well enough (probably a n00b at it  :Wink: ) to be able 
to give you a reliable answer. Isnt VB Script more like this code would be as if it was written using Late Binding?

----------


## MartinLiss

Here is the script file I use.


VB Code:
<!--
+---------------------------------------------------------------------------+
     Function:    Spell Checker
    Description: This script uses Microsoft Word to check the spelling in 
                 posts. Word is assumed to be present.
 +---------------------------------------------------------------------------+
-->
 <SCRIPT LANGUAGE = "VBScript">   
    
Dim objWord
Dim objDoc
Dim objWindow
Dim objSource
Dim objSelect
Dim objSelectRange
Dim strResult 
 Set objWindow = window.external.menuArguments
Set objSource = objWindow.event.srcElement
Set oDocument = objWindow.document
Set objSelect = oDocument.selection
Set objSelectRange = objSelect.createRange()
'Create a new instance of word Application
Set objWord = CreateObject("word.Application")
'new
'Dim dlg
'Set dlg = objWord.Dialogs
 If objSource.tagName = "TEXTAREA" Then
    select case objWord.version
        'Office 2000
        case "9.0"
            with objWord
                .WindowState = 2
                .Visible = True
            end with
            Set objDoc= objWord.Documents.Add( , ,1, True)
        'Office XP
        case "10.0"
            with objWord
                .windowstate = 2
                .Visible = False
            end with
            Set objDoc= objWord.Documents.Add( , ,1, True)
            with objWord
                .windowstate =2
                .Visible = True
            end with
        'Office 97
        case else ' Office 97
            Set objDoc= objWord.Documents.Add 
    end select
          objDoc.Content=objSelectRange.text 
        objDoc.CheckSpelling
'dlg(828).Show(0)
    strResult = left(objDoc.Content, len(objDoc.Content) - 1)
     ' This part may not work if you don't use IE
    If objSelectRange.text = strResult Then
        ' There were no spelling errors, so give the user a 
        ' visual signal that something happened
        window.alert("The spelling check is complete.")
    End If
         ' Replace the selected text with the corrected text
    objSelectRange.text = strResult
         'Clean up 
        objDoc.Close False
        Set objDoc= Nothing
        objWord.Application.Quit True
        Set objWord= Nothing
end if
 </SCRIPT>

----------


## RobDog888

Is this an addition to that VBF Add-In one of our members made? If not how are you executing it?

Does the Set dlg = objWord.Dialogs work?

The const value for the spellingandgrammER dialog is =  828

----------


## MartinLiss

> Is this an addition to that VBF Add-In one of our members made? If not how are you executing it?
> 
> Does the Set dlg = objWord.Dialogs work?
> 
> The const value for the spellingandgrammER dialog is =  828


Yes it all works and yes, it is a part of the "Forum Tool" that I mention in my signature. The code is in an htm file that via Registry entries is appended to the IE right-click context menu.

----------


## RobDog888

Martin, instead of checking for a string match between the doc and the string variable you may be able to use words error count 
instead and that may help bring the function to other browsers then IE.

VB Code:
oDoc.SpellingErrors.Count ;)

----------


## MartinLiss

I'll try it tomorrow.

----------


## GaryWilson

I am having one problem. I'm finding that if I happen to have another instance of Word open for another reason it will close it without asking and I will lose my original document. is there any code fix that you can think of that will leave my original word document alone?

-Gary

----------


## RobDog888

I have been thinking about this for a while and I had tested the code quite well too so I'm not sure yet. How are you implementing it? All in one form or in a module like I have? What version of Word are you running?

----------


## RobDog888

I am running 2003 and I havent been able to replicate Word closing down when a previous document already exists. Can you give more details on how your implementing it?

----------


## RobDog888

I even tried it with multiple separate instances of Word and still didnt close any word windows upon the spellchecker close.  :Confused:

----------


## Oliver1

Hi, in an Access Module I've copied and pasted the code above. Then in an access form I try the following.


VB Code:
Private Sub Command0_Click()
Me.Text1 = SpellMe(Me.Text1)
 End Sub
 Private Sub Command3_Click()
    InitializeMe
End Sub
   Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
    If KillMe = True Then
        moApp.Quit False
    End If
    Set moApp = Nothing
End Sub

The module gets called okay but errors out on the 
App.OleRequestPendingTimeout = 999999
if I tab this out it then errors out on
Clipboard.Clear

Where does App and clipboard come from eg what refereces do I need, or is this never going to work in Access VBA?
Anyway thanks in advance for any help

----------


## RobDog888

I moved your post to my CodeBank thread for the VB 6 version of my spellchecker. 

In Access there is no QueryUnload event so you need to use the Unload event

VB Code:
Private Sub Form_Unload(Cancel As Integer)
 End Sub

----------


## RobDog888

If your using Access only then you dont need any of the code other then using Access' built in spell checking.

VB Code:
Private Sub SpellMe()
    Application.DoCmd.RunCommand acCmdSpelling
End Sub

----------


## Oliver1

Sorry, getting confused in my old age, anyway the problem with that is it automatically checks the whole form which I don't want, as the form in question is huge.
Currently I spell check like so.


VB Code:
Public Function Spellcheck(TextStr As String) As String
  
     Set WordApp = CreateObject("Word.Application")
     WordApp.Documents.Add
     Dim wordrange As Word.Range
     Set wordrange = WordApp.ActiveDocument.Range(0, 0)
     wordrange.Text = TextStr
     WordApp.Visible = True
     WordApp.Activate
     wordrange.CheckSpelling , , True
     wordrange.CheckGrammar
     Spellcheck = wordrange.Text
     wordrange.Text = ""
     WordApp.Documents.Close (False)
     WordApp.Quit
     Set WordApp = Nothing
End Function

But this has odd glitches which I was hoping your code would sort out.

----------


## RobDog888

So your not using VB 6 at all and you dont want to use the built in spell checker? If you just select the textbox or text and the call the SpellMe procedure I just posted it will only check the selection or textbox only.

----------


## Oliver1

Sorry feel am being relly stupid here. I don't mean to be a pain.
Yes this is fully in access so not vb6 at all. 
Anyway have tried using
Application.DoCmd.RunCommand acCmdSpelling
It checks the spelling but then shoots off and spell checks other text boxes.
Which as this database form is used by some very uncomputer literate people I think this will confuse them no end.

----------


## RobDog888

Did you make a selection first?

----------


## Oliver1

Not sure what you mean tried higlighting the text and then doing it, but after it checked the highlighted text it moved on to another control.

----------


## RobDog888

It works in my test form with several textboxes. I highlight 1 and then spellcheck it and it doesnt check the rest of the textboxes.

VB Code:
Option Compare Database
 Private Sub SpellMe()
    Me.Text0.SelStart = 0
    Me.Text0.SelLength = Len(Me.Text0.Text)
    Application.DoCmd.RunCommand acCmdSpelling
End Sub
 Private Sub Form_Click()
    SpellMe
End Sub

----------


## Oliver1

Thanks that works, assume Access doesn't have a grammer checker though.

----------


## RobDog888

AFAIK, Access does not have a Grammer checker.

----------


## Oliver1

Thanks for you help.

----------


## RobDog888

Anytime  :Smilie: 

If you wanted the Grammer checker then you would need to have Word installed and use my original code - post #1.

----------


## AReilly

Hi 'Oliver1',
          I was just having a read through this thread and was wondering would you mind possibly giving me a sample of where/how you set the acCmdSpelling checks in VBA? ,when you were initially checking all the text boxes on the form?

Would be appreciated if possible,

Thanks  :Smilie:

----------


## allen177

I have just implemented this code in my app yesterday and have the following (small) problems. Firstly, when the user clicks to Spellcheck, the dialog box doesn't always come to the top and it makes the app seem as if it is stuck. Secondly, if they have any other Office app running, this app comes to the forefront immediately the button is pressed. My users are running Office 2003 if this is any help.
Thanks  :Smilie:

----------


## tony007

> I really can't narrow it down to a certain part of the code so I am posting it all in an attachment.



man i get this error:




```
Compile error:

User-defined type not defined
```

and pointing at :

*WithEvents objSysTray As vbSysTrayTools.SysTray*


could u tell me how to fix it i am using visual basic 6.thanks

----------


## RobDog888

Thats not in my code example but it loks like your missing a class or control in your project.

----------


## tony007

> Thats not in my code example but it loks like your missing a class or control in your project.


Thanks for u reply. Oh i was thinking it was u code but now i tried your code and i get the following error:

Compile error:

*User-defined type not defined*

and pointing at :

*Public moApp As Word.Application*


could u help me fix this error. I added one button and a textbox to the project. What else do i need such as refrences or any other controles?

Furthermore, is it possible to underline the spelling mistakes as we type and by clicking on mistake it gives suggestions? Also is it possible to make this program so it only does what i just described on external editboxes ? I be happy if u help me here.Thanks

----------


## RobDog888

Early binding:
Add a reference to MS Word xx.0 Object Library

It may be possible to catch spelling mistakes as you type but it would need calls to spellcheck after each keypress. What do you mean "external textboxes"? Not your program but someone elses? If so that would also be possible but not something that would be very easy.

----------


## aconybeare

RobDog, Martin,

Did you ever get this converted or working with the vb-forum tool?

Cheers Al

----------


## RobDog888

No I didnt at least but I did start working on writting an AddOn for IE7  :Big Grin:

----------


## aconybeare

Hi,

I've attempted to translate this code into vbscript for use with the vb-world forum tool

Can be easily altered to be used with regular web forms

Cheers Al

----------


## Hiroshi

Hi, I just have one question.  Is there a way to have spellcheck, but just like do it all in the background. like have a array of words to either check (true and keep) or don't (false and throw-out)  If this thread is too old or something and I'm posting on a dead thread, just tell me.  I'm not sure what the rules are on all that.  Thanks

----------


## RobDog888

The thread is still alive lol.  :Big Grin: 

Yes, you can get the spelling suggestions with the GetSpellingSuggestions function which returns a collection of possible spelling replacements.

----------


## Hiroshi

One more thing. if you would. maybe this should go somewhere else. but anyway. I saw the reference I needed but now I've found out I need to link it. and I'm not sure how I am to go about this. (never done it before)

----------


## Hiroshi

I'm trying to use your module and then use  moApp.Checkspelling("ttest")
and I don't know why but it says that:

Run-time error '91':

Object variable or with block variable not set
// 
I don't understand.

----------


## RobDog888

Are you calling the InitializeMe procedure first anywhere in your app?

----------


## Ogmius

Awsome code, but im havnig an issue where it closes all isntances of word... if I am working on a word document, it closes without asking me, and it shows an additional document that shows the text it is spell checking... odd

----------


## RobDog888

Thanks  :Smilie: 

Place a breakpoint on the InitializeMe sub and check if the mbKillMe flag is True or False when you do have Word already running.

----------


## danasegarane

VB Code:
'Add a reference to MS Word xx.0 Object Library
'1.Select Project From the tools menu
'2.Select Reference ,In the shown dialog box, tick the check box before
 '  Microsoft Word x.x object Library.
'3.Run the project

----------


## oldmanbernie

I'm wondering if you can help me out.  Here is my version of the spell check code.  In random occasions, I would encounter "Run-time error '462'".  I looked it up on http://support.microsoft.com/kb/189618, and it seems to indicate that VB did not release the reference to word, and it interferes with automation code when the code is run more than once.

I have played around with the code to resolve the issue, but I'm out of ideas.  I have even tried running some "throw-exceptions" at the end, but the code won't recognize the error number.

This issue does not happen all the time, but it seems to happen intermittantly at random times.  I am wondering if any of you have had experience with this.

The following is my code and thanks for your help!


VB Code:
Public moApp As Object
Private mbKillMe As Boolean
 Public Property Get KillMe() As Boolean
    InitializeMe
    KillMe = mbKillMe
End Property
 Public Property Let KillMe(Value As Boolean)
    mbKillMe = Value
End Property
 Public Sub InitializeMe()
    On Error Resume Next
    Set moApp = GetObject(, "Word.Application")
    If TypeName(moApp) <> "Nothing" Then
        Set moApp = GetObject(, "Word.Application")
    Else
        Set moApp = CreateObject("Word.Application")
        mbKillMe = True
    End If
End Sub
 Public Function SpellMe(ByVal msSpell As String) As String
     On Error GoTo No_Bugs
     Dim oDoc As Object 'Word.Document
    Dim iWSE As Integer
    Dim iWGE As Integer
    Dim sReplace As String
    Dim lResp As Long
     If msSpell = vbNullString Then Exit Function
    InitializeMe
    Select Case moApp.Version
        Case "9.0", "10.0", "11.0"
            Set oDoc = moApp.Documents.Add(, , 1, True)
        Case "8.0"
            Set oDoc = moApp.Documents.Add
        Case Else
            MsgBox "Unsupported Version of Word.", vbOKOnly + vbExclamation, "VB/Office Guru SpellChecker"
            SpellMe = msSpell
            Exit Function
    End Select
    Screen.MousePointer = vbHourglass
    App.OleRequestPendingTimeout = 999999
    oDoc.Words.First.InsertBefore msSpell
    iWSE = oDoc.SpellingErrors.Count
    iWGE = oDoc.GrammaticalErrors.Count
    
    If iWSE > 0 Or iWGE > 0 Then
        moApp.Assistant.On = False
        moApp.Visible = False
        If (moApp.WindowState = 0) Or (moApp.WindowState = 1) Then
            moApp.WindowState = 2
        Else
            moApp.WindowState = 2
        End If
        moApp.Dialogs(828).Application.Options.CheckGrammarWithSpelling = True
        moApp.Dialogs(828).Application.Options.SuggestSpellingCorrections = True
        moApp.Dialogs(828).Application.Options.IgnoreUppercase = True
        moApp.Dialogs(828).Application.Options.IgnoreInternetAndFileAddresses = True
        moApp.Dialogs(828).Application.Options.IgnoreMixedDigits = False
        moApp.Dialogs(828).Application.Options.ShowReadabilityStatistics = False
        moApp.Visible = True
        moApp.Activate
        lResp = moApp.Dialogs(828).Display
        If lResp < 0 Then
            moApp.Visible = True
            MsgBox "Corrections Being Updated!", vbOKOnly + vbInformation, App.ProductName
            Clipboard.Clear
            oDoc.Select
            oDoc.Range.Copy
            sReplace = Clipboard.GetText(1)
            If (InStrRev(sReplace, Chr(13) & Chr(10))) = (Len(sReplace) - 1) Then
                sReplace = Mid$(sReplace, 1, Len(sReplace) - 2)
            End If
            SpellMe = sReplace
        ElseIf lResp = 0 Then
            MsgBox "Spelling Corrections Have Been Canceled!", vbOKOnly + vbCritical, "VB/Office Guru SpellChecker"
            SpellMe = msSpell
        End If
    Else
        MsgBox "No Spelling Errors Found" & vbNewLine & "Or No Suggestions Available!", vbOKOnly + vbInformation, _
        "VB/Office Guru SpellChecker"
        SpellMe = msSpell
    End If
    oDoc.Close False
    Set oDoc = Nothing
    If KillMe = True Then
        moApp.Visible = False
    End If
    Screen.MousePointer = vbNormal
    Exit Function
No_Bugs:
    If Err.Number = "91" Then
        SpellMe = msSpell
        Resume Next
    ElseIf Err.Number = "462" Then
        SpellMe = msSpell
        MsgBox "Spell Checking Is Temporary Un-Available!" & vbNewLine & "Make sure an e-mail message is not open.", _
        vbInformation, "ActiveX Server Not Responding"
        Screen.MousePointer = vbNormal
    ElseIf Err.Number = 429 Then
        SpellMe = msSpell
        Set moApp = Nothing
        Resume Next
    Else
        SpellMe = msSpell
        MsgBox Err.Number & " " & Err.Description, vbOKOnly + vbInformation, App.ProductName
        Screen.MousePointer = vbNormal
    End If
End Function

----------


## RobDog888

Without getting into it yet, only have limited time, have you checked to see if on those systems where you get the error if they have Outlook open and if so does it use Word as its default email editor. If it does and they have an email message open it may be being used by my spell check code as the open instance. So when they close an email its closing word and geting the 462 error.

----------


## oldmanbernie

That was one of the tests I did.  I was getting the error without having outlook open.

----------


## RobDog888

But did you have any email messages open either? You can have an email open without having Outlook fully open.  :Wink: 

Also, did you check the status in the InitializeMe() sub? What is the value of mbKillMe at the end of the sub?

----------


## oldmanbernie

good advice rob.

I'll be monitoring the status of mbKillMe.  This issue happens intermittantly, so I'll have to keep testing it and wait for it to pop up.

Thanks for the help.

----------


## superbovine

VB Code:
'VB.net 2005
'Based on example fro another site, However modified.
'The example simple moved the Application off the screen which did not work well if Word every crashed during a spell check because it would start off the screen.
'This uses this example of WdWindowState.wdWindowStateMinimize
 Imports System.Runtime.InteropServices
Imports Word
'Imports Microsoft.Office.Interop.Word
  Public Class SpellCheck
     Inherits System.Windows.Forms.Form
     ' Invokes either the spell or grammar checker.  
    Private Sub SpellOrGrammarCheck(ByVal blnSpellOnly As Boolean)
        Try
            ' Create Word and temporary document objects.
            Dim objWord As Word.Application
            Dim objTempDoc As Object
            ' Declare an IDataObject to hold the data returned from the 
            ' clipboard.
            Dim iData As IDataObject
             ' If there is no data to spell check, then exit sub here.
            If TextBox1.Text = "" Then
                Exit Sub
            End If
            objWord = New Word.Application
            'objWord = New Microsoft.Office.Interop.Word.Application
            objTempDoc = objWord.Documents.Add
            objWord.Visible = False
             'Minimze word
             If (objWord.ActiveWindow.WindowState <> WdWindowState.wdWindowStateMinimize) Then
                objWord.ActiveWindow.WindowState = WdWindowState.wdWindowStateMinimize
            End If
               ' Copy the contents of the textbox to the clipboard
            Clipboard.SetDataObject(TextBox1.Text)
             ' With the temporary document, perform either a spell check or a 
            ' complete
            ' grammar check, based on user selection.
            With objTempDoc
                .Content.Paste()
                .Activate()
                If blnSpellOnly Then
                    .CheckSpelling()
                Else
                    .CheckGrammar()
                End If
                  ' After user has made changes, use the clipboard to
                ' transfer the contents back to the text box
                .Content.Copy()
                iData = Clipboard.GetDataObject
                If iData.GetDataPresent(DataFormats.Text) Then
                    TextBox1.Text = CType(iData.GetData(DataFormats.Text), _
                        String)
                End If
                 .Saved = True
                .Close()
            End With
              objWord.Quit()
             'MessageBox.Show("The spelling check is complete.", _
            '    "Spell Checker", MessageBoxButtons.OK, _
            '    MessageBoxIcon.Information)
             ' Microsoft Word must be installed. 
        Catch COMExcep As Runtime.InteropServices.COMException
            MessageBox.Show( _
                "Microsoft Word must be installed for Spell/Grammar Check " _
                & "to run.", "Spell Checker")
         Catch Excep As Exception
            MessageBox.Show("An error has occured.", "Spell Checker")
         End Try
     End Sub
     Private Sub btnSpellCheck_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnSpellCheck.Click
        SpellOrGrammarCheck(True)
    End Sub
     'Private Sub btnGrammarCheck_Click(ByVal sender As System.Object, _
    '   ByVal e As System.EventArgs) Handles btnGrammarCheck.Click
    '   SpellOrGrammarCheck(False)
    'End Sub
   End Class

----------


## RobDog888

Yes, I do have a VB.NET version of my code too:
http://www.vbforums.com/showthread.php?t=359879

----------


## scmay

> Thats not in my code example but it loks like your missing a class or control in your project.



Is it possible to get those red underlines on error words detected using this spell checker?

----------


## RobDog888

The Word Object Model doesnt expose that exact wavy underlinning but it does have a close similar match. 

Specify the wdUnderlineWavy and .UnderlineColor to best duplicate the spellchecking spelling error identifier. Its very close.

This is in Word 2007 so I cant say its in the previous versions. 



```
Selection.Font.Underline = wdUnderlineWavy
Selection.Font.UnderlineColor = wdColorRed
```

----------


## scmay

Hi RobDog888,

For some reason when I implement your code in the system accessing localhost database it works fine, however when it is using the server database the spellcheck functionality does not function. I know it is still accessing and opening MS Word (because the temp files in MS Word keep increasing invisibly, when you open a new MS Word you realize the instance has incremented), but I am not sure how to fix this...or why this should happen.

----------


## jmargel

I am using the code in an access 2000 database.  I have a richtextbox using it as a mini-word application.  When I run the code it says the spelling is complete (no spelling errors) but it's clear that I do have them.  I will just type in a bunch of letters and it passes.  

I noticed then in word it would do the same thing, I had to delete the custom.dic file to get word correctly working again with the default dictionary.  However the problem still presists in my application.

Has anyone got this working in an access or richtextbox environment?

----------


## jmargel

For RichTextBoxes I found another piece of code that works much better.  Create a button and put this in the code.  RTFText is the name of your RichTextBox.  I'm using this in Access 2000 and it is working great.



```
On Error GoTo SpellCheckErr
	Dim oWord As Object

	Set oWord = CreateObject("Word.Application")

	'Save the RTF Box contents to a temporary file
	rtfText.SaveFile "C:\TEST.RTF", rtfRTF

	'Open the saved document and spellcheck it
	oWord.Documents.Open ("C:\TEST.RTF")
	oWord.ActiveDocument.SpellingChecked = False
	oWord.Options.IgnoreUppercase = False
	oWord.ActiveDocument.CheckSpelling

	'Save the changes to the RTF file & close
	oWord.ActiveDocument.Save
	oWord.ActiveDocument.Close
	oWord.Quit

	'Load the changes back to the rtf text box.
	rtfText.LoadFile "C:\TEST.RTF", rtfRTF

	Set oWord = Nothing
	Screen.MousePointer = vbDefault
	MsgBox "Spell Check is complete", _
		vbInformation, "Spell Check"
	Exit Sub

SpellCheckErr:
	MsgBox Err.Description, vbCritical, _
		"Spell Check"
	Set oWord = Nothing
```

----------


## RobDog888

You may run into issues with different OS' and permissions to write a file to a particular directory. 
For ex. in Vista writting to the root drive is locked down and prohibited. This wopuld mean writting to some other location and dont think that yoiu could use the Program Files directory as that is locked down too. )

----------


## bikertz

In your code for spelling and grammer checking, is there a way to hide the Check Grammer checkbox on the Spelling and Grammer dialog? I want to force the user to have both spelling and grammer checked without providing the option to disable the grammer checking. Also, is there a way to disable the Options button on the Spelling and Grammer dialog?

----------


## VBLearner6

Finally, which code I can use in my VB6 program for spell-check? Please help me out.

Thanks.

----------


## RobDog888

> Finally, which code I can use in my VB6 program for spell-check? Please help me out.
> 
> Thanks.


Whats your question/issue?

----------


## RobDog888

> In your code for spelling and grammer checking, is there a way to hide the Check Grammer checkbox on the Spelling and Grammer dialog? I want to force the user to have both spelling and grammer checked without providing the option to disable the grammer checking. Also, is there a way to disable the Options button on the Spelling and Grammer dialog?


To modify any control on Words spell checker dialog (other then prepopulating it) you would need to use a C++ dll to subclass Word and modify the dialog via APIs. A bit of work but can be done.

----------


## zepar

Hi guys, thank you for this great thread. I am using Visual Basic 2005.

I have code similar to this and the spell checker is working. 

The problem I am having is if the user brings up the spell checker dialog window and then switches to another application and then alt-tabs back to my application, things freeze up.

The user can alt-tab back to the Word dialog box and close it, but if he tries to go directly to the application it freezes.

Does the line: "App.OleRequestPendingTimeout = 999999" prevent this freezing, and if not is there another way to fix this?

Thanks again  :Smilie:

----------


## zepar

Didn't realize above message saved, srry for the double post

----------


## RobDog888

No prob and Thanks  :Smilie: 

Since you are using .NET you should be using something similar to my VB.NET version:
http://www.vbforums.com/showthread.php?t=359879

In .NET perhaps creating a separate thread to process the spellchecking may solve the siiue  :Wink: 

I'm working on a new updated version and shold be ready soon  :Smilie:

----------


## zepar

I tried the code and am still having the freezing issue when the user tabs out to another app and then back to my app while the spellchecker is still running, so I put in a workaround where I will show Word in the task bar below and they can click on that to get back to the spellchecker and avoid freezing.

Thanks again for your help  :Smilie:

----------


## RobDog888

No prob. 

What version of Word are you using so we can track any issues with a particular version?

----------


## zepar

Word 2003 (Word 11.5604.8202)

----------


## GARY MICHAEL

Hello,

I tried this code and got this error.



```
Error: User defined type not defined.

Public moApp As Word.Application
```

I copied and pasted your code to a module then
I cut the bottom part and pasted it into a form.

Where did I go wrong?

----------


## si_the_geek

Rather than _just_ copy+paste code from somewhere, you should at least read the comments at the top of it:



> ```
> 'Early binding:
> 'Add a reference to MS Word xx.0 Object Library
> 'Modifications: none.
>  
> 'Late binding:
> 'No references needed to any version of Word
> 'Modifications: Change object vars definitions (moApp & oDoc) to Object
> 'Change constants to their numeric equilivalents.
> ```

----------


## RobDog888

You are better off using Late Binding as I remember reading your Word Processor thread.

----------


## GARY MICHAEL

I did read the notes and still didn't know what it meant. 
If I had examples of binding or whatever, it would help. I
could then figure out what does what.

----------


## RobDog888

Checck out this FAQ
http://www.vbforums.com/showthread.php?t=406640

----------


## GARY MICHAEL

A little too complicated for me. I think I'll just 
stick with trying to figure out how to disable the 
visualizations in Window Media Player control, 
using a button. Is there a code for that?
I'd like to give the user an option to use it or not.

----------


## RobDog888

Its not hard. If you look at teh two coding examples of Early vs Late you can see the only differences are ...

Early:
Add a reference to Word (or whatever you are automating)


Late:
No reference needed
Declare variables as Object
Declare Constants yourself as no reference means they wont be declared

For the WMP question, have you tried a search yet?

Ps, dont give up so soon.  :Wink:

----------


## GARY MICHAEL

Thanks for the encouragement.

----------


## RobDog888

Post up any more questions or issues you come across and we all would be happy to help.

----------


## SNIPER.PS

Thanks for the code

----------


## frozie

Good Work  :Smilie:

----------


## Mart

Moring All, first time here - exciting!

I'm trying to get this goint in Access for 2 reasons: 1. it looks awsome and I like it therfore I want to (already got the built in one working fine but you know  :Smilie: ) 2. Acess 2007 runtime doesn't have a spell check and I need to add one.

I've imported the code and popped it into a new module. I've already got a reference to word 11 so I'm guessing I'm in with early binding (in 2003 at the mo, work out 2007 later).

Just running debug and had to change the mouse pointer to 11 which makes me think I should be using late binding?? Anyway, whilst debuggin, it stops at App.OleRequestPendingTimeout = 999999 with a variable not defined - I'm guessing I need to either add a reference or make a change in accordance with late binding? Not sure how though, any help would be greatly appreciated.

Martyn

----------


## allen177

I have been using this code quite successfully for some time but have now hit a problem.  The scenario is a VB6.0 application using Office 2010 spell check.  Sometimes it works and sometimes the users get a message stating that Spell check is currently unavailable.  Below is the code from my app:



```
Public Function SpellMe(ByVal msSpell As String) As String

    On Error GoTo No_Bugs

    Dim oDoc As Word.Document
    Dim iWSE As Integer
    Dim iWGE As Integer
    Dim sReplace As String
    Dim lresp As Long

    If msSpell = vbNullString Then Exit Function
    InitializeMe
    
    If gDiags Then
        frmDiags.AddLine moApp.Version
    End If
    
    Select Case moApp.Version
        Case "9.0", "10.0", "11.0", "12.0", "14.0"
            Set oDoc = moApp.Documents.Add(, , 1, True)
        Case "8.0"
            Set oDoc = moApp.Documents.Add
        Case Else
            MsgBox "Unsupported Version of Word.", vbOKOnly + vbExclamation, "VB/Office Guru™ SpellChecker™"
            Exit Function
    End Select
    
    Screen.MousePointer = vbHourglass
    App.OleRequestPendingTimeout = 999999
    oDoc.Words.First.InsertBefore msSpell
    iWSE = oDoc.SpellingErrors.count
    iWGE = oDoc.GrammaticalErrors.count
    '<CHECK SPELLING AND GRAMMER DIALOG BOX>
    If iWSE > 0 Or iWGE > 0 Then
        '<HIDE MAIN WORD WINDOW>
        moApp.Visible = False
        If (moApp.WindowState = wdWindowStateNormal) Or (moApp.WindowState = wdWindowStateMaximize) Then
            moApp.WindowState = wdWindowStateMinimize
        Else
            moApp.WindowState = wdWindowStateMinimize
        End If
        '</HIDE MAIN WORD WINDOW>
        '<PREP CHECK SPELLING OPTIONS DIALOG BOX (MODIFY TO YOUR PREFERENCES)>
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.options.CheckGrammarWithSpelling = True
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.options.SuggestSpellingCorrections = True
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.options.IgnoreUppercase = True
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.options.IgnoreInternetAndFileAddresses = True
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.options.IgnoreMixedDigits = False
        moApp.Dialogs(wdDialogToolsSpellingAndGrammar).Application.options.ShowReadabilityStatistics = False
        '</PREP CHECK SPELLING OPTIONS DIALOG BOX (MODIFY TO YOUR PREFERENCES)>
        '<DO ACTUAL SPELL CHECKING>
        moApp.Visible = True
        moApp.Activate
        lresp = moApp.Dialogs(wdDialogToolsSpellingAndGrammar).display
        '</DO ACTUAL SPELL CHECKING>
        If lresp < 0 Then
            moApp.Visible = True
            MsgBox "Corrections Being Updated!", vbOKOnly + vbInformation, App.ProductName
            Clipboard.Clear
            oDoc.Select
            oDoc.Range.copy
            sReplace = Clipboard.GetText(1)
            '<FIX FOR POSSIBLE EXTRA LINE BREAK AT END OF TEXT>
            If (InStrRev(sReplace, Chr(13) & Chr(10))) = (Len(sReplace) - 1) Then
                sReplace = Mid$(sReplace, 1, Len(sReplace) - 2)
            End If
            '</FIX FOR POSSIBLE EXTRA LINE BREAK AT END OF TEXT>
            SpellMe = sReplace
        ElseIf lresp = 0 Then
            MsgBox "Spelling Corrections Have Been Canceled!", vbOKOnly + vbCritical, "VB/Office Guru™ SpellChecker"
            SpellMe = msSpell
        End If
    Else
        MsgBox "No Spelling Errors Found" & vbNewLine & "Or No Suggestions Available!", vbOKOnly + vbInformation, _
        "VB/Office Guru™ SpellChecker"
        SpellMe = msSpell
    End If
    '</CHECK SPELLING AND GRAMMER DIALOG BOX>
    oDoc.Close False
    Set oDoc = Nothing
    '<HIDE WORD IF THERE ARE NO OTHER INSTANCES>
    If KillMe = True Then
        moApp.Visible = False
    End If
    '</HIDE WORD IF THERE ARE NO OTHER INSTANCES>
    Screen.MousePointer = vbNormal
    Exit Function
No_Bugs:
    If err.Number = "91" Then
        Resume Next
    ElseIf err.Number = "462" Then
        MsgBox "Spell Checking Is Temporary Un-Available!" & vbNewLine & "Try Again After Program Re-Start.", _
        vbOKOnly + vbInformation, "ActiveX Server Not Responding"
        Screen.MousePointer = vbNormal
    ElseIf err.Number = 429 Then
        Set moApp = Nothing
        Resume Next
    Else
        MsgBox err.Number & " " & err.Description, vbOKOnly + vbInformation, App.ProductName
        Screen.MousePointer = vbNormal
    End If
End Function
```

Any help would be greatly appreciated.

Thanks.

----------


## RobDog888

I dont have 2010 installed on my work computer but have you tried stepping through the code to see where the hangup lies?

----------


## allen177

It fails at Set oDoc = moApp.Documents.Add(, , 1, True) in that at the next step it says "the action cannot be performed as no document is open" or "Spell Check is currently unavailable".  As far as Word 2010 goes it isn't just affecting this Spell Check code but everywhere I need to automate Word.

Thanks

----------


## KProvance

Rob,
I reworked your code into a "drop in" class module that does it's own initializing and termination, negating the user doing so in their form code.  I also added some extra properties and events.  Your copyright suggests I should ask permission before posting it here.  Would it be okay to do so?

Thanks!

- Kev

----------


## KProvance

Hopefully this thread is still being followed?  Maybe?   :Smilie: 

I discovered something in your sample that doesn't make sense, and damned if I can find the answer in MSFT's docs.

If you change the CheckGrammarWithSpelling option to false, and click Cancel on the Dialog, lResp returns -1 (versus 0 for Cancel/Close).  Switching it back to True restores normal behaviour.

So, any idea why that might be?

I'm tossing around checking the spelling errors count for something > 0 as clicking Cancel does not lower the error count like Ignore does.

----------


## RobDog888

If memory servers me right, the calcel/close values are not self explainatory. There is also a third value -2 which means something too.

I will dig up my old files and see what somments I have from r n d.

----------


## KProvance

Rob -

The MSDN says the following (http://msdn.microsoft.com/en-us/libr...g.display.aspx)

-2 = The Close button.

-1 = The OK button.

0 (zero) = The Cancel button.

> 0 (zero) = A command button: 1 is the first button, 2 is the second button, and so on.

My observation is, based on the Grammar check set to false is the return value is always -1, regardless what button is clicked.  Odd behaviour to say the least (but with MSFT, this is typically the norm, especially when ti comes to automating various office classes).  As I noted before, I was able to compensate for this by checking for unchecked errors after the user cancels out.  Couldn't figure out why the return value is so flaky, so...

I'd still like to get your permission to post my class based on your code.  I think you'd find the enhancements nod worthy.  ;-)

----------


## abbid_siddiqui

Today i have also come up with the same problem. Everything works fine but when you try to use Word 2010, it gives the following error. However my error description is slightly different
4605 The Add method or property is not available because the document is a rich text edit control.

----------


## abbid_siddiqui

> Today i have also come up with the same problem. Everything works fine but when you try to use Word 2010, it gives the following error. However my error description is slightly different
> 4605 The Add method or property is not available because the document is a rich text edit control.


I've found out the reason for this problem but don't have any idea how to resolve this? The error occurs when there is an unclosed instance of Spell Checker in the Task Manager (don't know why it remains in task manager). If you close that and re-run the application, it works.
Rob, could you please let me know how to avoid this error?

----------


## ColinE66

> I wrote this to demonstrate how to take full advantage of MS Word's built in Spelling and Grammer checker


Oh, the irony...

----------

