0
votes

I'm a beginner at coding, so please bear with me. Is there any way to use the function If to insert text (using TypeText), and then change the font of that text added using VBA Word?

So I'll give you some information on what I am working on; I am using the following code to count the number of spelling mistakes in a document.

Sub countErrors()
    MsgBox (ActiveDocument.SpellingErrors.count)
End Sub

What I would like to do is use an If function to the number of spelling mistakes present. If there are any spelling mistakes I want to insert text at the top of the document saying "REJECTED " with font in red, bold and size 14. Is there any way to do this using the If function?

I tried adding the following to the above code;

Sub countErrors()
    Msgbox (ActiveDocument.SpellingErrors.count)
    If SpellingErrors <= 1 then
    Selection.HomeKey unit:=wdStory
    With Selection
        .Font.Size = 14
        .Font.ColorIndex = wdRed
        .Font.Bold = True
    End With
    Selection.TypeText ("REJECTED ")
    End If
End Sub

The code just counts the number of spelling mistakes and displays a MsgBox with it, and then that's where the code ends -- it doesn't add any text, etc.

Can someone please let me know where I am going wrong? This is extremely frustrating.

Thank you in advance.

1
Could be ` If SpellingErrors <= 1 then` means "less then or equal to 1`. I'm afraid your code is REJECTED. (Automatic homework rejection because a word is used that isn;t in Office's [very limited] dictionary?.. Brutal! I wouldn't want to be in your class!) - ashleedawg
MsgBox (ActiveDocument.SpellingErrors.count) should be just MsgBox ActiveDocument.SpellingErrors.count - AJD
How many spelling errors do you see in the MsgBox when you run your code? If you comment out the If and End If lines, so that your code always runs, no matter how many spelling errors there are - does it format and type the text? - Cindy Meister

1 Answers

0
votes

Your code needs to check if SpellingErrors is greater than zero.

Sub CountErrors()

MsgBox "The document currently has " & ActiveDocument.SpellingErrors.Count & " spelling error(s)."

If ActiveDocument.SpellingErrors.Count > 0 Then
    Selection.HomeKey unit:=wdStory
    With Selection
        .Font.Size = 14
        .Font.ColorIndex = wdRed
        .Font.Bold = True
        .TypeText "REJECTED"
    End With
End If

End Sub