Please Note: This article is written for users of the following Microsoft Word versions: 2007, 2010, 2013, 2016, 2019, and Word in Microsoft 365. If you are using an earlier version (Word 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Word, click here: Running Macros Based on Keywords.

Running Macros Based on Keywords

Written by Allen Wyatt (last updated June 1, 2023)
This tip applies to Word 2007, 2010, 2013, 2016, 2019, and Word in Microsoft 365


1

Eyal wonders if there is any way to run a macro automatically if a user types in a particular word or phrase.

Unfortunately, there are no Word VBA event procedures that will detect when text is typed into a document. However, Word internally detects when a complete word is entered so that it can carry out such things as spell checking, AutoCorrect, and updating the word count. You cannot tap into this internal detection method, however.

Probably the best approach is to use VBA's timer capability to check whether a word has been entered. (Remember—Word internally updates the word count every time a word is completed, so your timer code can monitor the word count to see if it has changed.) The OnTime method has a minimum setting of one second, which means that your timer-based code can only run once per second. It is possible for a fast typist to type more than one word per second, so your code needs to actually check the last few words entered.

Here is the code you can use:

Dim wCount As Long
Dim aRange As Range
Dim tWords
Dim inactiveSW As Boolean

Sub InitializeTimer()
    tWords = Array("APPLE", "ORANGE", "PEAR")
    wCount = ActiveDocument.Words.Count
    Set aRange = Selection.Range
    aRange.Start = ActiveDocument.Range.Start
    inactiveSW = False
    StartTimer
End Sub
Public Sub StartTimer()
    Application.OnTime When:=Now + TimeValue("00:00:01"), _
    Name:="TestWords"
End Sub
Public Sub TestWords()
    Dim testWord As String
    Dim i As Long
    Dim k As Long
    Dim kw As Long
    Dim xc As Long

    If inactiveSW Then Exit Sub
    With ActiveDocument
        xc = .Range.Words.Count - wCount
        If xc > 0 And xc < 5 Then
            aRange.End = Selection.End
            kw = aRange.Words.Count - 1
            If kw > 0 Then
                For k = kw - xc + 1 To kw
                    testWord = UCase(Trim(aRange.Words(k).Text))
                    For i = 0 To UBound(tWords)
                        If testWord = tWords(i) Then
                            mysub (testWord)
                            Exit For
                        End If
                    Next i
                Next k
            End If
        End If
        wCount = .Range.Words.Count
    End With
    StartTimer
End Sub
Public Sub KillOnTime()
  'cannot stop the timer so set inactive switch
  inactiveSW = True
End Sub
Sub mysub(s As String)
  ' this subroutine is executed when a special word is entered
  MsgBox s
End Sub

The first routine you need to run is the InitializeTimer macro. It sets up the variables that are necessary before actually starting the OnTime method. It then calls the StartTimer macro which actually sets the timer that runs the TestWords macro.

TestWords checks to see if the word count has increased and, if it has, it checks the last five words entered to see if they match any of your trigger words. (The trigger words are set in the tWords array, in the InitializeTimer macro. They should be entered in the array all in uppercase.) If a trigger word is detected, then your code (mysub) is executed, and the trigger word is passed to your code.

It should be noted that it may be possible for the word count to jump by more than five, particularly if text is pasted into the document. If you want the code to check all words that may be pasted into the document, then you'll need to change the checking code line, which is this:

        If xc > 0 And xc < 5 Then

All you need to do is change it to this:

        If xc > 0 Then

If you want to stop the word checking, run the KillOnTime macro, which sets a flag that stops the words from being checked. To later restart checking, just run InitializeTimer again.

Note:

If you would like to know how to use the macros described on this page (or on any other page on the WordTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (12375) applies to Microsoft Word 2007, 2010, 2013, 2016, 2019, and Word in Microsoft 365. You can find a version of this tip for the older menu interface of Word here: Running Macros Based on Keywords.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Moving Groups of Data Labels at One Time

Having problems working with data labels in your charts? That's not unusual; here's an idea of an add-in that could help ...

Discover More

Changing the Size of a Drawing Object

Documents are often made up of more than just text. If you have drawing objects in your document, you will doubtless need ...

Discover More

Removing Add-ins

Add-ins are used to extend Excel's capabilities in lots of different ways. If you want to get rid of an add-in ...

Discover More

Create Custom Apps with VBA! Discover how to extend the capabilities of Office 2013 (Word, Excel, PowerPoint, Outlook, and Access) with VBA programming, using it for writing macros, automating Office applications, and creating custom applications. Check out Mastering VBA for Office 2013 today!

More WordTips (ribbon)

Determining How Many Styles are Available

Got a macro that processes or uses styles? You definitely need to know how many styles Word has available in the ...

Discover More

Determining the Horizontal Position of the Insertion Point

Need to figure out how far the insertion point is from the left margin? You can do so by using this small macro that ...

Discover More

Adding Automatic Time Stamps

Your computer knows the current date and time, and Word provides ways you can get that date and time into your document. ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is two more than 7?

2024-03-27 16:54:24

Craig Martin

I have another Application.OnTime already running and understand you can only have one Application.OnTime running at a time.

Is there a workaround to not use application.OnTime for the above program.

Thank you


This Site

Got a version of Word that uses the ribbon interface (Word 2007 or later)? This site is for you! If you use an earlier version of Word, visit our WordTips site focusing on the menu interface.

Videos
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.