How to caculate number of words in a page of word document I need the VB code for this action that will allow me to automate calculation of word count that will be place at the footer of each page
I tries searching for solution but no luck
CodePudding user response:
Unless you're prepared to insert 'Next Page' Section breaks between your pages, you cannot have the individual page counts in the page headers or footers. The following code does the required calculations and inserts the page counts as hidden text at the top of each page's body text. Content in page headers, footers, footnotes, endnotes & textboxes is ignored.
Sub Demo()
Application.ScreenUpdating = False
Dim p As Long, w As Long, Rng As Range
With ActiveDocument
For p = .ComputeStatistics(wdStatisticPages) To 1 Step -1
Set Rng = .GoTo(What:=wdGoToPage, Count:=p).GoTo(What:=wdGoToBookmark, Name:="\Page")
With Rng
w = .ComputeStatistics(wdStatisticWords)
.Collapse wdCollapseStart
.Text = "[" & w & "]"
.Font.Hidden = True
End With
Next
End With
Application.ScreenUpdating = True
End Sub
Do note that I have not used the .Words.Count property as that is unreliable.
CodePudding user response:
Word Count Property:
Option Explicit
Sub Output_Word_Count()
Dim WordCount As Long
WordCount = ThisDocument.Words.Count
MsgBox "Total Word Count:=" & WordCount & ".", vbInformation vbOKOnly, "WORDCOUNT"
End Sub
Result:
Continuation:
I'm adding this answer to your comment here for the sake of completion and so future visitors may be able to take a look, but as discussed in comments above, .ComputeStatistics(wdStatisticWords)
is more reliable so I would encourage you to use @macropod 's version.
Sub Test()
Dim iPage As Long
Dim PageCount As Long
Dim tmpWordCount As Long
With ThisDocument
PageCount = .ComputeStatistics(wdStatisticPages)
Debug.Print PageCount
For iPage = 1 To PageCount
Selection.GoTo wdGoToPage, wdGoToAbsolute, iPage
tmpWordCount = .Bookmarks("\Page").Range.Words.Count
Debug.Print tmpWordCount
.Bookmarks("\Page").Select
.Bookmarks("\Page").Range.Words(tmpWordCount).Select
Selection.InsertBefore Text:=vbNewLine & " -> PageCount = " & tmpWordCount & " "
Next iPage
End With
End Sub