vba 如何可靠地获取 Word 文档中的页数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16894257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:25:22  来源:igfitidea点击:

How can I reliably get the number of pages in a Word document?

vbams-wordword-vbaword-2010

提问by Gary McGill

I am making lots of changes to a Word document using automation, and then running a VBA macro which - among other things - checks that the document is no more than a certain number of pages.

我正在使用自动化对 Word 文档进行大量更改,然后运行 ​​VBA 宏,除其他外,该宏检查文档的页数是否不超过一定数量。

I'm using ActiveDocument.Information(wdNumberOfPagesInDocument)to get the number of pages, but this method is returning an incorrect result. I think this is because Word has not yet updated the pagination of the document to reflect the changes that I've made.

我正在使用ActiveDocument.Information(wdNumberOfPagesInDocument)获取页数,但此方法返回了错误的结果。我认为这是因为 Word 尚未更新文档的分页以反映我所做的更改。

ActiveDocument.ComputeStatistics(wdStatisticPages)also suffers from the same issue.

ActiveDocument.ComputeStatistics(wdStatisticPages)也有同样的问题。

I've tried sticking in a call to ActiveDocument.Repaginate, but that makes no difference.

我试过坚持调用ActiveDocument.Repaginate,但这没什么区别。

I did have some luck with adding a paragraph to the end of the document and then deleting it again - but that hack seems to no longer work (I've recently moved from Word 2003 to Word 2010).

我确实很幸运地在文档末尾添加了一个段落,然后再次将其删除 - 但该 hack 似乎不再起作用(我最近从 Word 2003 移至 Word 2010)。

Is there any way I can force Word to actuallyrepaginate, and/or wait until the repagination is complete?

有什么办法可以强制 Word实际重新分页,和/或等到重新分页完成?

回答by alexkovelsky

Try (maybe after ActiveDocument.Repaginate)

尝试(也许之后ActiveDocument.Repaginate

ActiveDocument.BuiltinDocumentProperties(wdPropertyPages)

It is causing my Word 2010 to spend half-second with "Counting words" status in status bar, while ActiveDocument.ComputeStatistics(wdStatisticPages)returns the result immediately.

这导致我的 Word 2010 在状态栏中的“计数单词”状态花费半秒钟,同时ActiveDocument.ComputeStatistics(wdStatisticPages)立即返回结果。

Source: https://support.microsoft.com/en-us/kb/185509

来源:https: //support.microsoft.com/en-us/kb/185509

回答by Kris K

I just spent a good 2 hours trying to solve this, and I have yet to see this answer on any forum so I thought I would share it.

我刚刚花了 2 个小时试图解决这个问题,我还没有在任何论坛上看到这个答案,所以我想我会分享它。

https://msdn.microsoft.com/en-us/vba/word-vba/articles/pages-object-word?f=255&MSPPError=-2147217396

https://msdn.microsoft.com/en-us/vba/word-vba/articles/pages-object-word?f=255&MSPPError=-2147217396

That gave me my solution combined with combing through the articles to find that most of the solutions people reference are not supported in the newest versions of Word. I don't know what version it changed in, but my assumption is that 2013 and newer can use this code to count pages:

这给了我我的解决方案,并结合文章的梳理发现人们引用的大多数解决方案在最新版本的 Word 中不受支持。我不知道它更改了哪个版本,但我的假设是 2013 年及更新版本可以使用此代码来计算页数:

ActiveDocument.ActiveWindow.Panes(1).Pages.Count.

I believe the way this works is ActiveDocument selects the file, ActiveWindow confirms that the file to be used is in the current window (in case the file is open in multiple windows from the view tab), Panes determines that if there is multiple windows/split panes/any other nonsense you want the "first" one to be evaluated, pages.count designates the pages object to be evaluated by counting the number of items in the collection.

我相信这种工作方式是 ActiveDocument 选择文件,ActiveWindow 确认要使用的文件在当前窗口中(如果文件在视图选项卡的多个窗口中打开),Panes 确定是否有多个窗口/拆分窗格/您希望评估“第一个”的任何其他废话, pages.count 通过计算集合中的项目数来指定要评估的 pages 对象。

Anyone more knowledgeable feel free to correct me, but this is the first method that gave me the correct page count on any document I tried!

任何知识渊博的人都可以随时纠正我,但这是第一种在我尝试过的任何文档上为我提供正确页数的方法!

Also I apologize but I cant figure out how to format that line into a code block. If the mods want to edit my comment to do that be my guest.

我也很抱歉,但我无法弄清楚如何将该行格式化为代码块。如果模组想编辑我的评论来做我的客人。

回答by Andy G

After you've made all your changes, you can use OnTimeto force a slight delay before reading the page statistics.

完成所有更改后,您可以OnTime在阅读页面统计信息之前使用强制稍微延迟。

Application.OnTime When:=Now + TimeValue("00:00:02"), _
        Name:="UpdateStats"

I would also update all the fields before this OnTimestatement:

我还将更新此OnTime语句之前的所有字段:

ActiveDocument.Range.Fields.Update

回答by Dan McSweeney

I found a possible workaround below, if not a real answer to the topic question. Yesterday, the first ComputeStatisticsline below was returning the correct total of 31 pages, but today it returns only 1.

我在下面找到了一个可能的解决方法,如果不是主题问题的真正答案。昨天,ComputeStatistics下面的第一行返回了正确的总共 31 页,但今天只返回了 1 页。

The solution is to get rid of the Contentobject and the correct number of pages is returned.

解决方法是去掉Content对象并返回正确的页数。

Dim docMultiple As Document
Set docMultiple = ActiveDocument 
lPageCount = docMultiple.Content.ComputeStatistics(wdStatisticPages)  ' Returns 1
lPageCount = docMultiple.ComputeStatistics(wdStatisticPages)  ' Returns correct count, 31

回答by Saurav Dubey

ActiveDocument.Range.Information(wdNumberOfPagesInDocument)

ActiveDocument.Range.Information(wdNumberOfPagesInDocument)

This works every time for me. It returns total physical pages in the word.

这对我来说每次都有效。它返回单词中的总物理页数。

回答by anthony Judd

I used this from within Excel it worked reliably on about 20 documents none were longer than 20 pages but some were quite complex with images and page breaks etc.

我在 Excel 中使用了它,它在大约 20 个文档上可靠地工作,没有一个超过 20 页,但有些文档非常复杂,包含图像和分页符等。

Sub GetlastPageFromInsideExcel()
Set wD = CreateObject("Word.Application")
Set myDoc = wD.Documents.Open("C:\Temp\mydocument.docx")
myDoc.Characters.Last.Select        ' move to end of document
wD.Selection.Collapse               ' collapse selection at end
lastPage = wD.Selection.Information(wdActiveEndPageNumber)
mydoc.close
wd.quit
Set wD = Nothing
End Sub

回答by soko8

Dim wordapp As Object
Set wordapp = CreateObject("Word.Application")
Dim doc As Object
Set doc = wordapp.Documents.Open(oFile.Path)

Dim pagesCount As Integer
pagesCount = doc.Content.Information(4) 'wdNumberOfPagesInDocument
doc.Close False
Set doc = Nothing