VBA word count problem or bug? RRS feed

  • Question

  • Hi,

    I have been using the following code in VBA to count the number of words in a word document using Word.Count. The result is always one more word (e.g. If my word document has four words in it, the word count would show as 5 words)

    this is my code:

    sub countingWordsInWord()

        Dim count As Long

        count = ActiveDocument.Words.Count

        MsgBox (count)

    End sub

    Could you please explain me why this happens

    Thank you


    Tuesday, November 28, 2017 9:38 PM

All replies

  • The explanation is simple. What Word considers to be a 'word' to be counted and what you do are not necessarily the same. As your macro counts 'words' in the document, then this will include the paragraph mark at the end of the document which the application also considers a 'word'. Punctuation will also affect the count.

    You might find

    count = ActiveDocument.BuiltInDocumentProperties("Number of Words")
    will give you a more accurate count.

    Graham Mayor - Word MVP

    Wednesday, November 29, 2017 5:28 AM