Vba word number of words

Count Words in Selection

This Word VBA Macro will count the number of words in the selection. If no selection is made, it will count the number of words in the entire document.

Sub WordCount()
'counts whole doc, then word Count for selection (if something is selected)
    Dim nWordsCount As Long
    Dim nCharCount As Long



    nWordsCount = ActiveDocument.Range.ComputeStatistics(wdStatisticWords)
    nCharCount = ActiveDocument.Range.ComputeStatistics(wdStatisticCharacters)
    MsgBox "The entire doc contains: " & vbCrLf & nWordsCount & " words and" & vbCrLf & _
           nCharCount & " characters without spaces", , "Word Count"

    'now show word count for selected text

    If Selection.Words.Count >= 1 And Selection.Type <> wdSelectionIP Then
        nWordsCount = Selection.Range.ComputeStatistics(wdStatisticWords)
        nCharCount = Selection.Range.ComputeStatistics(wdStatisticCharacters)

        MsgBox "Selected text contains: " & vbCrLf & nWordsCount & " words and" & vbCrLf & _
               nCharCount & " characters without spaces", , "Word Count (selection)"

    End If
End Sub

I periodically receive long documents that include footnotes and am trying to find a way using VBA to count the number of words on each page, including footnotes. It doesn’t matter if a footnote spills over onto the next page, I just the word count including footnotes that are anchored on the page.

I have a macro that correctly counts the number of words in the body of the text, using the command:

WordCount = ActiveDocument.Range(Start:=pos1, End:=pos2).ComputeStatistics(wdStatisticWords)

The variables pos1 and pos2 have been set to the first and last characters of the page being counted.

However, when I add the True parameter to ComputeStatistics(wdStatisticWords, True), to IncludeFootnotesAndEndnotes, as in:

WordCount = ActiveDocument.Range(Start:=pos1, End:=pos2).ComputeStatistics(wdStatisticWords, True)

it doesn’t work, giving an error that there are too many parameters. It appears that when using a Range, the IncludeFootnotesAndEndnotes parameter is not available.

How do you count the words within footnotes contained in a range?

GB


  • #1

Hi, couple of minor problems. I wanted to help my wife with a macro that
would count all the words in the document and also the number of words in
bold. I can’t even get to first base on this because the VBA word count
seems to be all screwy.

For example: ‘MsgBox ActiveDocument.Range.Words.Count’ returns an answer of
10 for a document that has 5 words in it. The word count on the menu
Tools…word count gives the correct answer. Is there a simple way to access
that, and why does words.count not just ummm count the words?

BTW this is Word 2003, and it’s up to date with all the patches.

Advertisements

Jay Freedman


  • #2

GB said:

Hi, couple of minor problems. I wanted to help my wife with a macro
that would count all the words in the document and also the number of
words in bold. I can’t even get to first base on this because the VBA
word count seems to be all screwy.

For example: ‘MsgBox ActiveDocument.Range.Words.Count’ returns an
answer of 10 for a document that has 5 words in it. The word count on
the menu Tools…word count gives the correct answer. Is there a
simple way to access that, and why does words.count not just ummm
count the words?
BTW this is Word 2003, and it’s up to date with all the patches.

The Words collection contains a separate item for each punctuation mark,
each paragraph mark, and each inline graphic in the document. That makes it
unsuitable for your purpose. The number in the Word Count dialog, which
matches the usual English definition of «words», is instead available from
the ComputeStatistics method.

Here’s sample code that you can modify to your taste:

Sub demo()
Dim WordCount As Long
Dim myRange As Range

Set myRange = ActiveDocument.Range

WordCount = myRange.ComputeStatistics(wdStatisticWords)
MsgBox WordCount & » words»

‘ now count bold words
WordCount = 0
With myRange.Find
.ClearFormatting
.Format = True
.Text = «»
.Font.Bold = True
.Forward = True
.Wrap = wdFindStop
While .Execute
WordCount = WordCount + 1
myRange.Collapse wdCollapseEnd
Wend
End With
MsgBox WordCount & » bold words»
End Sub


Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.

Helmut Weber


  • #3

Hi GB,

select all of the doc.

MsgBox Selection.Words.Count
MsgBox Selection.Range.ComputeStatistics(wdStatisticWords)

The second comes closer to what you want,
though it is regrettable that Word uses different
methods for word count.

… macro that would count the number of words in bold.

For example: ‘MsgBox ActiveDocument.Range.Words.Count’ returns an answer of
10 for a document that has 5 words in it. The word count on the menu
Tools…word count gives the correct answer. Is there a simple way to access
that, and why does words.count not just ummm count the words?

What a word constitutes,
is a fuzzy concept of fuzzy naturally language.
You would need a fuzzy computer, a contradiction in itself,
to count words, and it would return a fuzzy answer…

Try this, which is refinable at nauseam,
but will never be perfect.

Sub Test14()
Dim lBld As Long
Dim rDcm As Range
Dim oWrd As Range
Set rDcm = ActiveDocument.Range
For Each oWrd In rDcm.Words
If oWrd.Font.Bold And Len(oWrd) > 1 Then
lBld = lBld + 1
End If
Next
MsgBox lBld
End Sub

Greetings from Bavaria, German
Helmut Weber MVP WordBVA
(MA linguistics)

GB


  • #4

The Words collection contains a separate item for each punctuation mark,
each paragraph mark, and each inline graphic in the document. That makes
it unsuitable for your purpose. The number in the Word Count dialog, which
matches the usual English definition of «words», is instead available from
the ComputeStatistics method.

Thanks very much, Jay. Your code (snipped) does the job nicely. That raises
another question, namely where is there a fairly simple beginner’s guide to
the Word object model? The trouble with the help file is that it explains
how to use a particular property or method, but it’s not so good at helping
to find the right one in the first place.

GB


  • #5

Jay Freedman said:

With myRange.Find
.Forward = True
.Wrap = wdFindStop
While .Execute
WordCount = WordCount + 1
myRange.Collapse wdCollapseEnd
Wend
End With

I was curious why the line ‘myRange.Collapse wdCollapseEnd’ needs to be
there? I’m quite surprised that it works, as I would expect it to collapse
the range you are finding in whilst still finding bold words in it. It seems
to work quite nicely with or without that line in it.

Jay Freedman


  • #6

GB said:

I was curious why the line ‘myRange.Collapse wdCollapseEnd’ needs to
be there? I’m quite surprised that it works, as I would expect it to
collapse the range you are finding in whilst still finding bold words
in it. It seems to work quite nicely with or without that line in it.

The behavior of the Find object is something that defies understanding.

When the .Execute method succeeds (and returns True), the .Start and .End
values of the Range object are changed to cover the found text. You can
watch this happening in the Locals window as you single-step (F8) in the
code. In some hidden bit of memory, though, VBA remembers the original range
and continues to search through it. The exception to this occurs when the
body of the While loop modifies the content of the Range object by adding or
removing text, or by changing the .Start or .End value. That’s when the
..Collapse is required; if it’s omitted, the next .Execute will indeed search
within the _current_ location of the Range object.

Rather than forget the .Collapse when it is needed, and because it does no
harm if it isn’t needed, I have a standard «template» for a Find loop that
includes it. Yes, you can take it out.


Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.

Advertisements

Jay Freedman


  • #7

Thanks very much, Jay. Your code (snipped) does the job nicely. That raises
another question, namely where is there a fairly simple beginner’s guide to
the Word object model? The trouble with the help file is that it explains
how to use a particular property or method, but it’s not so good at helping
to find the right one in the first place.

I can’t say I’ve kept up with what’s in print on this subject. After all this
time, I just carry around large chunks of the object model in my head :) and
use the help and the Object Browser (F2 in the VBA editor) to refresh my memory
when necessary.

There’s a fairly good introduction to the concepts at
<http://msdn2.microsoft.com/en-us/library/aa272082(office.11).aspx>.

If you ask the help for the topic «Word Object Model (Table)» you’ll get a
diagram of the top levels. Each box in the table is hyperlinked to the topic
about that object, and the topic has links at the top for Properties, Methods,
and (where applicable) Events.

If you’re looking for a property or method and you don’t know what it’s called,
or what object it belongs to, use the Object Browser. Type into the search box
any term or fragment that you think might be related to what you want, and click
the Search (binoculars) button. You’ll get a list of everything in the object
model whose names contain that fragment.

Jay Prakash


  • #8

when I try to write the name of the active word file name to another opened word file, it writes onle the opened file with below said way. Can you help to resolve it?

Code:
ActiveDocument.Name

Thanks
JP

Advertisements

Jay Freedman


  • #9

When you have more than one document open at the same time, the variable «ActiveDocument» refers to the document that has the focus (the active cursor) at the instant that line of the macro is
executed. If the macro changes the focus (for example, by opening another document or by using the Activate method), the ActiveDocument changes too. So «ActiveDocument» could refer to different
documents at different times during the execution of the single macro.

The way to work around this is to declare and initialize one or more variables of type Document, and use those variables instead of ActiveDocument. For example:

Sub Demo()
Dim FirstDoc As Document
Dim SecondDoc As Document

Set FirstDoc = ActiveDocument
‘ so FirstDoc is the document that had the focus when the macro started

Set SecondDoc = Documents.Add ‘ open a new blank document, which becomes ActiveDocument

MsgBox «When macro started, » & FirstDoc.Name & » was active»
MsgBox «Now » & SecondDoc.Name & » is active»
End Sub

Вот цитата из справки, которая, надеюсь, реально вам поможет.

This example displays the number of words in the active document, including footnotes*.

Visual Basic for Applications

Visual Basic
1
2
MsgBox ActiveDocument.ComputeStatistics(Statistic:=wdStatisticWords,  IncludeFootnotesAndEndnotes:=True) _
 & "words"

Только основной текст (без колонтитулов, сносок, врезок и прочего) вообще просто:

Visual Basic
1
MsgBox ActiveDocument.ComputeStatistics wdStatisticWords

_______________
* показывает число слов в активном документе, включая колонтитулы

Добавлено через 10 минут
А можно программно вызвать статистику Word: Ввести предложение, посчитать число слов в предложении

Below we will look at a program in Excel VBA that counts the number of words in a selected range. One or more spaces are assumed to separate words.

Situation:

Count Words in Excel VBA

1. First, we declare two Range objects and three variables. We call the Range objects rng and cell. One Integer variable we call cellWords, one Integer variable we call totalWords, and one String variable we call content.

Dim rng As Range, cell As Range
Dim cellWords As Integer, totalWords As Integer, content As String

2. We initialize the Range object rng with the selected range and the two variables of type Integer with value 0.

Set rng = Selection
cellWords = 0
totalWords = 0

3. We want to check each cell in a randomly selected range (this range can be of any size). In Excel VBA, you can use the For Each Next loop for this. Add the following code lines:

For Each cell In rng

Next cell

Note: rng and cell are randomly chosen here, you can use any names. Remember to refer to these names in the rest of your code.

4. Next, we determine for each cell in this range how many words it contains. To ignore a cell that contains a formula, add the following code line between For Each and Next (only if cell.HasFormula is false we continue).

If Not cell.HasFormula Then

End If

5. First, we write the content of the cell to the variable content. Next, we remove the spaces at the beginning and the end (if there are any). In Excel VBA, you can use the Trim function for this. For example, » excel vba» will be converted to «excel vba». Add the following code lines in your If statement.

content = cell.Value
content = Trim(content)

Note: the trim function in Excel VBA does not remove extra spaces between words, but that’s OK in this example.

6. At this point, a cell can still be empty. If the cell is empty, we assign the value 0 to the variable cellWords. If not, it contains at least one word and we assign the value 1 to the variable cellWords. Add the following code lines in your If statement.

If content = «» Then
    cellWords = 0
Else
    cellWords = 1
End If

A cell can contain more than one word of course. That’s exactly what we want to find out now. As an example we take: «excel vba». If a cell contains at least one space at this stage, it contains at least one more word. You can use the Instr function in Excel VBA to look for a space. Instr(content, » «) finds the position of the first space in content.

7. We will make use of the Do While Loop structure. Code placed between these words (at step 8, 9 and 10) will be repeated as long as the part after Do While is true. We want to repeat these steps as long as Instr(content, » «) > 0 is true (as long as content contains a space and thus more words). Add the Do While Loop in your If statement.

Do While InStr(content, » «) > 0

Loop

8. Next, we take the part of content starting at the position of the first space. We use the Mid function for this.

content = Mid(content, InStr(content, » «))

For example: Mid(«excel vba», InStr(«excel vba», » «)) will give » vba».

9. We trim the string again.

content = Trim(content)

Result: «vba»

10. We increment cellWords by 1.

cellWords = cellWords + 1

This Do While Loop will be repeated as long as content contains a space and thus more words. In our example, we exit the Do While Loop since «vba» does not contain a space anymore! Result: this cell contains 2 words.

11. After having checked one cell, we add cellWords to the variable totalWords. This code line should be placed outside the Do While Loop but in the If statement.

totalWords = totalWords + cellWords

The whole process starts again for the next cell until all cells have been checked.

12. Finally, we display the value of totalWords using a msgbox. This code line should be placed outside the For Each Next loop.

MsgBox totalWords & » words found in the selected range.»

13. Test the program.

Result:

Count Words result

Понравилась статья? Поделить с друзьями:
  • Vba word выделенный текст в переменную
  • Vba word no spacing
  • Vba word insert text
  • Vba word insert table
  • Vba word if text not found