Vba word количество страницам

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.

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.ComputeStatistics(wdStatisticPages) also suffers from the same issue.

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

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).

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

braX's user avatar

braX

11.5k5 gold badges20 silver badges33 bronze badges

asked Jun 3, 2013 at 10:03

Gary McGill's user avatar

Gary McGillGary McGill

26k25 gold badges117 silver badges200 bronze badges

17

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.

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:

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.

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.

Gary McGill's user avatar

Gary McGill

26k25 gold badges117 silver badges200 bronze badges

answered Jan 30, 2018 at 22:19

Kris K's user avatar

1

Try (maybe after 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.

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

answered Jul 15, 2015 at 8:41

alexkovelsky's user avatar

alexkovelskyalexkovelsky

3,7911 gold badge27 silver badges21 bronze badges

5

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

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

I would also update all the fields before this OnTime statement:

ActiveDocument.Range.Fields.Update

answered Jun 15, 2013 at 11:19

Andy G's user avatar

Andy GAndy G

19.1k5 gold badges49 silver badges69 bronze badges

1

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

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

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

dwitvliet's user avatar

dwitvliet

7,0647 gold badges36 silver badges62 bronze badges

answered Jul 17, 2014 at 15:21

Dan McSweeney's user avatar

1

ActiveDocument.Range.Information(wdNumberOfPagesInDocument)

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

4b0's user avatar

4b0

21.7k30 gold badges95 silver badges140 bronze badges

answered Oct 26, 2017 at 4:11

Saurav Dubey's user avatar

1

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.

Sub GetlastPageFromInsideExcel()
Set wD = CreateObject("Word.Application")
Set myDoc = wD.Documents.Open("C:Tempmydocument.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

answered Mar 23, 2020 at 7:36

anthony Judd's user avatar

One problem I had in getting «ComputeStatistics» to return a correct page count was that I often work in «Web Layout» view in Word. Whenever you start Word it reverts to the last view mode used. If Word was left in «Web Layout» mode «ComputeStatistics» returned a page count of «1» page for all files processed by the script. Once I specifically set «Print Layout» view I got the correct page counts.

For example:

$MSWord.activewindow.view.type = 3    # 3 is 'wdPrintView', 6 is 'wdWebView'
$Pages = $mydoc.ComputeStatistics(2)  # 2 is 'wdStatisticPages'

answered Feb 17, 2022 at 1:48

Lewis Newton's user avatar

You can use Pages-Object and its properties such as Count. It works perfect;)

Dim objPages As Pages
Set objPage = ActiveDocument.ActiveWindow.Panes(1).Pages

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

answered Sep 27, 2022 at 20:01

Sultan Khan's user avatar

1

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

answered May 30, 2019 at 5:42

soko8's user avatar

soko8soko8

11 bronze badge

1

Exclsius

0 / 0 / 0

Регистрация: 12.12.2019

Сообщений: 22

1

16.09.2020, 13:10. Показов 8066. Ответов 7

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Всем добрый день!
Пытаюсь посчитать количество страниц в Word-документе, код следующий:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Dim objWord As Object
Dim MyRange As Excel.Range
Dim FileStart
Dim intWords As Integer
Dim i&, r As Range, st&, en&
'Dim WdRange As Object
   
    
 
Set objWord = CreateObject("Word.Application")
 
    FileSt = "Путь" 'путь исходного файла
 
    
    Set objDoc = objWord.Documents.Open(FileSt)
    
      objWord.Visible = True
 
 objDoc.Activate
NumPages = objWord.ActiveDocument.Content.ComputeStatistics(wdStatisticPages)
'NumPages = objWord.ActiveDocument.Range.Information(wdActiveEndAdjustedPageNumber)
'NumPages = objWord.ActiveDocument.BuiltinDocumentProperties("Number of pages")
 
 MsgBox (NumPages)

Пробую 3 разных варианта — первый почему-то возвращает число слов
Второй возвращает ошибку
А третий всегда возвращает цифру 6, хотя, количество страниц в документе всегда разное (это документ накопительного типа, то есть сегодня 10, завтра 15, послезавтра 20).
Вопрос в том — почему может возвращать всегда одинаковое число? Может, в настройках самого документа, а не кода что-то посмотреть?



0



1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

16.09.2020, 13:46

2

кажется это сочетание
objWord.ActiveDocument — ни к чему, что-то одно …
пока проекспериементируйте на активном документе, а уж потом изошряйтесь



0



0 / 0 / 0

Регистрация: 12.12.2019

Сообщений: 22

16.09.2020, 14:39

 [ТС]

3

Ципихович Эндрю, разницы-то никакой нет, меняю NumPages = objWord.ActiveDocument.BuiltinDocumentProperties(» Number of pages»)

На NumPages = objDoc.BuiltInDocumentProperties(«Number of pages») — ничего не меняется, вывод неверный что там, что там. Вопрос в том, откуда он берет именно конкретную цифру 6, когда в документе больше страниц. И почему по wdStatisticPages выводит не страницы, а количество слов…



0



Narimanych

2630 / 1636 / 744

Регистрация: 23.03.2015

Сообщений: 5,141

16.09.2020, 15:32

4

Лучший ответ Сообщение было отмечено Exclsius как решение

Решение

Exclsius,
Используйте константы:

Добавлено через 3 минуты
Exclsius,
Используйте константы.
В вашем примере
NumPages = objWord.ActiveDocument.Content.ComputeStatistics(wdStatisticPages)
замените на
NumPages =objDoc.ComputeStatistics(2)

Как вариант:

Visual Basic
1
2
3
4
5
6
7
8
9
10
Sub MMM()
FileSt = "Путь" 'путь исходного файла
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(FileSt)
           objWord.Visible = False
            MsgBox (objDoc.ComputeStatistics(2))
            objDoc.Close
            objWord.Quit
          
End Sub



0



ᴁ®

Эксперт MS Access

3069 / 1735 / 361

Регистрация: 13.12.2016

Сообщений: 5,937

Записей в блоге: 4

16.09.2020, 15:45

5

Exclsius, такое поле в любом месте документа покажет количество страниц
{NUMPAGES # «0» * MERGEFORMAT}

Миниатюры

Подсчет количества страниц в Word документе
 



0



0 / 0 / 0

Регистрация: 12.12.2019

Сообщений: 22

16.09.2020, 15:50

 [ТС]

6

Narimanych, спасибо большое! Действительно, сработало. А сможете подсказать, почему константы использовать лучше? И как узнать соответствие константы конкретному методу?



0



amd48

779 / 461 / 79

Регистрация: 18.05.2016

Сообщений: 1,242

Записей в блоге: 4

17.09.2020, 10:36

8

Цитата
Сообщение от Exclsius
Посмотреть сообщение

почему константы использовать лучше?

если константа с префиксом wd — это константа из библиотеки ворда. В экселе или vbs, например, по имени она будет не доступна. Но её значение можно использовать. Но в таком случае лучше объявить её вручную:

Visual Basic
1
Const wdStatisticPages = 2

Тогда в будущем будет проще понять, что это за константа. Лучше, чем магическое число 2



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

17.09.2020, 10:36

8

Формулировка задачи:

Всем здравствуйте!
Для определения количества страниц активного документа Word, использовал такой код:

количество страниц определялось корректно, до тех пор пока мне не попался файл, который лежит в приложении.
Объясните пожалуйста, почему в этом файле количество страниц определяется неверно?

Код к задаче: «VBA Word: Количество страниц документа»

textual

NumPages = ActiveDocument.ComputeStatistics(wdStatisticPages)

Полезно ли:

11   голосов , оценка 3.727 из 5

Добрый день. Нашла такой макрос, сама только начала с ними работать, поэтому пока сложно самой править, т.к. плохо понимаю, что здесь прописано.

Код
Sub PSize()
Dim A3 As Integer
Dim A4 As Integer
Dim i As Long
Dim R As Range

    A3 = 0
    A4 = 0
    Set R = ActiveDocument.Range
    For i = 1 To R.Information(wdActiveEndPageNumber)
        Set R = ActiveDocument.GoTo(What:=wdGoToPage, _
                                    Which:=wdGoToAbsolute, _
                                    Count:=i)
        Select Case R.PageSetup.PaperSize
            Case wdPaperA3
                A3 = A3 + 1
            Case wdPaperA4
                A4 = A4 + 1
        End Select
    Next
    Debug.Print "Общее число страниц А1 = " & A4 / 8+ A3 / 4

End Sub

Хотелось бы его изменить, чтобы он просматривал такие стандартные форматы, как а4, а3, а2, а1, а0

«Для каждого файла *.doc из списка пытаюсь получить количество страниц…»

Пишет ivan (sidorec.ivan[DOGGY]googlemail.com):

Здравствуйте!
Встретился со следующей проблемой: Для каждого файла *.doc из списка пытаюсь получить количество страниц ([B]wdPropertyPages[/B]). [COLOR=red]Получаемые значения не соответствуют действительности![/COLOR]. Список файлов представляет из себя строковый массив с именами файлов (path+name). Документы открываю в цикле: открываю, считываю количество страниц, закрываю документ. Возникает одна особенность: когда код прохожу ручками: все в норме: количество страниц адекватное, как только запускаю макрос — значения другие(меньше на порядок). Предполагал, что во время работы макроса количество страниц открываемого документа не успевает обновиться. Поставил задержку сначала в 1, потом 5 и т.д. секунд. Не помогло. Попробовал пройтись по абзацам, словам и в конце концов по символам документа, надеясь, что такая работа с документом позволит правильно подсчитать количество страниц. Не вышло.
Если есть идеи, прошу поделиться!

Особо не разбирался, но следующий несложный код на VBA, вставленный в документ Word, сработал, т.е. определил число страниц для каждого из кучи файлов, найденных на всём диске c:

Правда, я тут открывал-закрывал файлы и смотрел число страниц через ActiveDocument. Офис был версии XP, в младших версиях VBA вообще глючный.

Private Sub CommandButton1_Click()
 Dim mySFO As FileSearch
 Dim foundFile
 Dim s As String
 Set mySFO = Application.FileSearch
 Dim filename  As String
 Dim n As Integer
 With mySFO
  .NewSearch
  .LookIn = "c:"
  .SearchSubFolders = True
  .filename = "*.doc"
  .FileType = msoFileTypeWordDocuments
  If .Execute() > 0 Then
   For q = 1 To .FoundFiles.Count
    Documents.Open filename:=.FoundFiles(q)
    n = ActiveDocument.ComputeStatistics(wdStatisticPages)
    s = s & ActiveDocument.Name & "=" & n & Chr(13) & Chr(10)
    ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
   Next q
  End If
 End With
 MsgBox (s)
End Sub

Для простоты сам документ с макросом находился на другом диске ( d: ) — чтоб не пытался открывать сам себя.

Также должно быть разрешено выполнение макросов (в Word XP/2003 — меню Сервис, Параметры, вкладка Безопасность, кнопка Зашита от макросов…, выбрать уровень Средняя).

09.10.2009, 23:47 [11208 просмотров]


К этой статье пока нет комментариев, Ваш будет первым

Понравилась статья? Поделить с друзьями:
  • Vba word количество слов
  • Vba word количество абзацев
  • Vba word как установить
  • Vba word как узнать номер страницы
  • Vba word как удалить пустые строки