none
HOW TO? Count words in an email body using VB/VBA? RRS feed

  • Question

  • Seems like a simple thing, but I haven't found a direct answer to this anywhere on the Web:

    The task is to:

    (1) Programmatically count the number of words in an email.

    (2) Insert that count into the email

    NOTES:

    Needs to work with Outlook 2007-2013

    Will use first inside VBA module. Will eventually use this inside of an outlook add-in. Does that change the coding requirement at all?

    The other challenge is what to do on replies. Ideally, I'd like to count words in the reply, separate from the words in the message to which I am replying. Not sure that's possible / practical.

    Sunday, June 15, 2014 5:57 PM

Answers

  • Hi,

    According to your description, you want to count the number of words in an mail item and insert the count into the mail.

    In fact, there is no property or method to count the words in the item body directly in Outlook Object Model. For a workaround, I think you could resort to Inspector.WordEditor Property to convert the Inspector object to a Word Document object and use Words.Count property to return the number of words. Then you could use the Range.InsertAfter Method of Document object to insert the count number into the mail item.

    Here is a simple VBA code which could help you understand it. If you display a reply mail item as an Inspector, you could run the code. You could also refer to it to write a VB.Net code.

    Sub CountWords()
        Dim myInspector As Inspector
        Dim WordDoc As Word.Document
        Set myInspector = Application.ActiveInspector
        Set WordDoc = myInspector.WordEditor
        MsgBox WordDoc.Words.Count
        WordDoc.Range.InsertAfter WordDoc.Words.Count
    End Sub


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, June 16, 2014 10:09 AM
    Moderator
  • Hello Mike,

    1. You may treat the body as a regular string returned by the Body property of the MailItem class. However, the easiest way to count the number of words is using the Word object model. The Inspector class provides the WordEditorproperty which returns the Microsoft Word Document Object Model of the  message being displayed. Here is what MSDN states:

    The WordEditor property is only valid if the IsWordMail method returns True and the EditorType property is olEditorWord. The returned WordDocument object provides access to most of the Word object model.

    The VBA: How to Count the Occurrences of a Word or Phrase article provides the source code in VBA for getting the job done.

    Sub CountWordPhrase()
    
    Dim x, Response, ExitResponse
    Dim y As Integer
    
    ' If an error occurs, continue the macro.
    On Error Resume Next
    
    AskAgain:
    
    ' Ask for the text to count.
    x = InputBox("Type the word you want to count and then click OK." _
    & Chr$(13) & Chr$(13) & _
    "NOTE: This macro will find a whole word only. If the text you typed " _
    & "is part of a larger string, it will also be found.")
    
    ' If text typed is blank or spaces, then ask to quit.
    If x = "" Or x = " " Then
        ExitResponse = MsgBox("You either clicked Cancel or you did " & _
        "not type a word. Do you want to quit?", vbYesNo)
        
        If ExitResponse = 6 Then
            End
        Else
            ' If answer No to quit, then ask for text to count again.
            GoTo AskAgain
        End If
    Else
    
        ' Search for and count occurrences of the text typed.
        With ActiveDocument.Content.find
            Do While .Execute(FindText:=x, Forward:=True, Format:=True, _
               MatchWholeWord:=True) = True
                
               ' Display message in Word's Status Bar.
               StatusBar = "Word is counting the occurrences of the text " & _
               Chr$(34) & x & Chr$(34) & "."
               
               y = y + 1
            Loop
        End With
    
    ' Display Message Box with results.
    Response = MsgBox("The text " & Chr$(34) & x & Chr$(34) & " was found" _
    & Str$(y) & " times.", vbOKOnly)
    
    End If
    End Sub
    

    2. You may find the Chapter 17: Working with Item Bodies available in MSDN helpful. It describes all possible ways for working with bodies. The sample code in VBA is also available.

    > Will use first inside VBA module. Will eventually use this inside of an outlook add-in. Does that change the coding requirement at all? 

    VBA and COM add-ins are different things. The latter is preferred if you plan to distribute your code on multiple PCs. I'd recommend moving your code to the add-in and don't rely on the VBA because it can be edited/altered by other users/developers.

    > The other challenge is what to do on replies. Ideally, I'd like to count words in the reply, separate from the words in the message to which I am replying. Not sure that's possible / practical.

    You can get a substring until your signature, for example, and then search for specific words or just count them. Also, as a workaround, you can count the number of words in the initial email and store that number in a user property. Later, after a reply is ready, you can search for all entries minus the value stored in the property and calculated earlier. Thus, you will find the number of entries exactly in the reply content.

    Monday, June 16, 2014 10:29 AM

All replies

  • Hi,

    According to your description, you want to count the number of words in an mail item and insert the count into the mail.

    In fact, there is no property or method to count the words in the item body directly in Outlook Object Model. For a workaround, I think you could resort to Inspector.WordEditor Property to convert the Inspector object to a Word Document object and use Words.Count property to return the number of words. Then you could use the Range.InsertAfter Method of Document object to insert the count number into the mail item.

    Here is a simple VBA code which could help you understand it. If you display a reply mail item as an Inspector, you could run the code. You could also refer to it to write a VB.Net code.

    Sub CountWords()
        Dim myInspector As Inspector
        Dim WordDoc As Word.Document
        Set myInspector = Application.ActiveInspector
        Set WordDoc = myInspector.WordEditor
        MsgBox WordDoc.Words.Count
        WordDoc.Range.InsertAfter WordDoc.Words.Count
    End Sub


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, June 16, 2014 10:09 AM
    Moderator
  • Hello Mike,

    1. You may treat the body as a regular string returned by the Body property of the MailItem class. However, the easiest way to count the number of words is using the Word object model. The Inspector class provides the WordEditorproperty which returns the Microsoft Word Document Object Model of the  message being displayed. Here is what MSDN states:

    The WordEditor property is only valid if the IsWordMail method returns True and the EditorType property is olEditorWord. The returned WordDocument object provides access to most of the Word object model.

    The VBA: How to Count the Occurrences of a Word or Phrase article provides the source code in VBA for getting the job done.

    Sub CountWordPhrase()
    
    Dim x, Response, ExitResponse
    Dim y As Integer
    
    ' If an error occurs, continue the macro.
    On Error Resume Next
    
    AskAgain:
    
    ' Ask for the text to count.
    x = InputBox("Type the word you want to count and then click OK." _
    & Chr$(13) & Chr$(13) & _
    "NOTE: This macro will find a whole word only. If the text you typed " _
    & "is part of a larger string, it will also be found.")
    
    ' If text typed is blank or spaces, then ask to quit.
    If x = "" Or x = " " Then
        ExitResponse = MsgBox("You either clicked Cancel or you did " & _
        "not type a word. Do you want to quit?", vbYesNo)
        
        If ExitResponse = 6 Then
            End
        Else
            ' If answer No to quit, then ask for text to count again.
            GoTo AskAgain
        End If
    Else
    
        ' Search for and count occurrences of the text typed.
        With ActiveDocument.Content.find
            Do While .Execute(FindText:=x, Forward:=True, Format:=True, _
               MatchWholeWord:=True) = True
                
               ' Display message in Word's Status Bar.
               StatusBar = "Word is counting the occurrences of the text " & _
               Chr$(34) & x & Chr$(34) & "."
               
               y = y + 1
            Loop
        End With
    
    ' Display Message Box with results.
    Response = MsgBox("The text " & Chr$(34) & x & Chr$(34) & " was found" _
    & Str$(y) & " times.", vbOKOnly)
    
    End If
    End Sub
    

    2. You may find the Chapter 17: Working with Item Bodies available in MSDN helpful. It describes all possible ways for working with bodies. The sample code in VBA is also available.

    > Will use first inside VBA module. Will eventually use this inside of an outlook add-in. Does that change the coding requirement at all? 

    VBA and COM add-ins are different things. The latter is preferred if you plan to distribute your code on multiple PCs. I'd recommend moving your code to the add-in and don't rely on the VBA because it can be edited/altered by other users/developers.

    > The other challenge is what to do on replies. Ideally, I'd like to count words in the reply, separate from the words in the message to which I am replying. Not sure that's possible / practical.

    You can get a substring until your signature, for example, and then search for specific words or just count them. Also, as a workaround, you can count the number of words in the initial email and store that number in a user property. Later, after a reply is ready, you can search for all entries minus the value stored in the property and calculated earlier. Thus, you will find the number of entries exactly in the reply content.

    Monday, June 16, 2014 10:29 AM