Word vba number of pages

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

  • Remove From My Forums
  • Question

  • I would just like to add page numbers to the bottom right hand side of each page in a Word document that I created using Visual Basic. 

    I would like the page numbers to have the following format:  «Page 1 of 5», «Page 2 of 5», etc.,

    Does anyone know how to do this?

    Thanks in advance,

    Jim


    James Hutchinson

Answers

  • >>>I would like the page numbers to have the following format:  «Page 1 of 5», «Page 2 of 5», etc.,

    Does anyone know how to do this?<<<

    According to your description, I suggest that you could refer to below code:

    Imports Word = Microsoft.Office.Interop.Word
    Module Module1
    
        Sub Main()
            Dim wordApp As Word.Application
    
            wordApp = New Word.Application()
    
            wordApp.Visible = True
    
            wordApp.Documents.Open("D:\yourdocname.docx")
    
            wordApp.ActiveDocument.Sections(wordApp.ActiveDocument.Sections.Count) _
            .Footers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Select()
    
            With wordApp.Selection
                .Paragraphs(1).Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight
                .TypeText(Text:="Page ")
                .Fields.Add(Range:=wordApp.Selection.Range, Type:=Word.WdFieldType.wdFieldEmpty, Text:= _
                    "PAGE ", PreserveFormatting:=True)
                .TypeText(Text:=" of ")
                .Fields.Add(Range:=wordApp.Selection.Range, Type:=Word.WdFieldType.wdFieldEmpty, Text:= _
                    "NUMPAGES ", PreserveFormatting:=True)
            End With
    
    
            wordApp.ActiveDocument.Save()
            wordApp.Quit()
            wordApp = Nothing
    
        End Sub
    
    End Module
    

    • Marked as answer by

      Wednesday, February 24, 2016 3:25 PM

title ms.prod ms.assetid ms.date ms.localizationpriority

PageNumbers object (Word)

word

9090f96e-d898-ace6-35fa-f6e59c527ea2

06/08/2017

medium

PageNumbers object (Word)

A collection of PageNumber objects that represent the page numbers in a single header or footer.

Remarks

Use the PageNumbers property to return the PageNumbers collection. The following example starts page numbering at 3 for the first section in the active document.

ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary) _ 
 .PageNumbers.StartingNumber = 3

Use the Add method to add page numbers to a header or footer. The following example adds a page number to the primary footer in the first section.

With ActiveDocument.Sections(1) 
 .Footers(wdHeaderFooterPrimary).PageNumbers.Add _ 
 PageNumberAlignment:=wdAlignPageNumberLeft, _ 
 FirstPage:=False 
End With

To add or change page numbers in a document with multiple sections, modify the page numbers in each section or set the LinkToPrevious property to True.

Use PageNumbers (index), where index is the index number, to return a single PageNumber object. In most cases, a header or footer contains only one page number, which is index number 1. The following example centers the first page number in the primary header in the first section.

ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary) _ 
 .PageNumbers(1).Alignment = wdAlignPageNumberCenter

Methods

Name
Add
Item

Properties

Name
Application
ChapterPageSeparator
Count
Creator
DoubleQuote
HeadingLevelForChapter
IncludeChapterNumber
NumberStyle
Parent
RestartNumberingAtSection
ShowFirstPageNumber
StartingNumber

See also

Word Object Model Reference

[!includeSupport and feedback]

Приветствую всех читателей блога scriptcoding.ru. В данной статье мы рассмотрим коллекцию PageNumbers и объекты PageNumber, входящих в объектную модель Word, которые отвечают за нумерацию страниц в ворде.

При подготовке данного материала я столкнулся с некоторыми нестыковками… Так, в большинстве случаев у коллекции PageNumbers будет только один класс PageNumber, это и логично, так как нельзя сделать несколько «нумераций» страниц для одного раздела. Вторая нестыковка – если нумерация страниц в ворде для верхнего колонтитула начинается с заданного номера, то это автоматически влияет и на нумерацию для нижнего колонтитула. С одной стороны это понятно, какой смысл задавать различную нумерацию для верхнего и нижнего колонтитула, но, непонятно следующее…

Доступ к коллекции PageNumbers осуществляется через одноименное свойство объекта HeaderFooter, а тот в свою очередь, мы получаем через свойства Headers или Footers класса Section. Как видим, мы можем указать, для какого колонтитула (верхнего или нижнего) нужно задавать нумерацию в Word.

Содержание

  1. Коллекция PageNumbers – нумерация в Word
  2. Свойства – нумерация страниц в Word
  3. Методы – как сделать нумерацию в ворде
  4. PageNumber – Нумерация в ворде
  5. Свойства – нумерация страниц в ворде
  6. Методы – как в ворде сделать нумерацию страниц

Коллекция PageNumbers – нумерация в Word

Свойства – нумерация страниц в Word

делаем нумерацию  в ворд

ChapterPageSeparator— Возвращает или устанавливает разделитель, используемый между номером главы и страницы. Значение константы WdSeparatorType:

  • wdSeparatorColon — 2 — двоеточие.
  • wdSeparatorEmDash — 3 — подчеркнутое тире.
  • wdSeparatorEnDash — 4 — стандартное тире.
  • wdSeparatorHyphen — 0 — дефис.
  • wdSeparatorPeriod — 1 — период.

HeadingLevelForChapter— Возвращает или задает уровень заголовка (от 0 до 8), который применяется к названиям глав в документе.

IncludeChapterNumber– Значение true, если номер главы входит в номера страниц. Чтение и запись.

NumberStyle— Возвращает или задает значение константы WdPageNumberStyle, которая представляет собой стиль нумерации страниц в Word.

RestartNumberingAtSection– Если значение свойства установлено в true, то при вызове метода Add нумерация в ворде будет начинаться с числа 0. Если значение false – то нумерация будет начинаться с числа одни, а попытка переопределить начальный пункт нумерации ворд страницы с помощью свойства StartingNumber ничего не даст. Чтение и запись.

ShowFirstPageNumber– Значение true – происходит автоматическое добавление пункта для нумерации Word страницы в нижний колонтитул.

StartingNumber— Возвращает или устанавливает значение, которое определяет начало нумерации страниц в ворде. Указанный номер может быть виден или не виден на первой странице в зависимости от установок свойства ShowFirstPageNumber. Если свойство RestartNumberingAtSection установлено в false, то будет происходить переопределение свойства StartingNumber так, чтобы нумерация в Word продолжалась из предыдущего раздела

Application— Возвращает объект Application, представляющий приложение Microsoft Word.

Count— Возвращает число номеров страниц в коллекции. В большинстве случаев, колонтитулы содержат только один номер страницы, который является числом 1.

Методы – как сделать нумерацию в ворде

делаем нумерацию в word

Add(PageNumberAlignment, FirstPage) — Возвращает класс PageNumber, представляющий номера, добавленные в верхний или нижний колонтитул раздела. Оба параметра являются дополнительными.

PageNumberAlignment – Определяет положение номера, значение константы WdPageNumberAlignment:

  • wdAlignPageNumberLeft — 0 – По левому краю.
  • wdAlignPageNumberCenter — 1 — По центру.
  • wdAlignPageNumberRight — 2 – По правому краю.
  • wdAlignPageNumberInside — 3 – По левому краю.
  • wdAlignPageNumberOutside — 4 – По правому краю.

FirstPage – Если установлено значение false, то номер не добавляется к первой странице. Если этот аргумент опущен, параметры нумерации в ворде определяет свойство DifferentFirstPageHeaderFooter класса PageSetup.

Item(index) – Доступ к объекту PageNumber по его номеру в коллекции PageNumbers. Фактически, количество классов PageNumber ровно 1.

PageNumber – Нумерация в ворде

Свойства – нумерация страниц в ворде

нумерация в ворде страниц

Alignment— Возвращает или задает выравнивание для номера страницы. Значение константы WdPageNumberAlignment (смотрите выше).

Application— Возвращает объект Application, представляющий приложение Microsoft Word.

Index– Позиция элемента в коллекции. Только чтение.

Методы – как в ворде сделать нумерацию страниц

нумерация в word страниц

Copy() — Копирует заданный PageNumber в буфер обмена.

Cut()— Вырезает указанный PageNumber из документа и помещает его в буфер обмена.

Delete() — Удаляет указанный PageNumber. Фактически, мы отменяем нумерацию в Word для выбранного колонтитула

Select() – Выбор указанного PageNumber. После использования этого метода, следует использовать свойство Selection для работы с выбранным элементом.

Хорошо, с теоретической частью мы закончили, теперь можно приступить к программированию. Я приведу два примера кода на языке VBScript и JScript сервера сценариев Windows Script Host:

Пример программного кода на языке VBSCRIPT:

' ----------------------------------------------------------------------------
' Коллекция PageNumbers и объекты PageNumber
' Нумерация в Word
' PageNumbers.vbs
' ----------------------------------------------------------------------------
Option Explicit
 
dim oWord, oDoc, i, MyText, oRange1, oRange2
 
Set oWord = CreateObject("Word.Application")
Set oDoc = oWord.Documents
oDoc.Add()
oDoc.Add()
oWord.Visible = true
Set oRange1 = oDoc(1).Range()                           
Set oRange2 = oDoc(2).Range()
 
MyText = "Нумерация в ворде. "
 
' Вставляем 6 страниц в первый документ
For i=0 to 6
     With oRange1
                 .InsertParagraph()
                 .EndOf
                 .InsertBreak()
     End With
Next
 
'-------------------------------------------------------------------------------------------------------------------
' Формируем нумерацию страниц в Word вместе с заголовками для первого документа
'-------------------------------------------------------------------------------------------------------------------
oDoc(1).Content.Style = -2
oDoc(1).Content.ListFormat.ApplyListTemplate oWord.ListGalleries(3).ListTemplates(7)
 
With oDoc(1).Sections(1).Headers(1).PageNumbers
    .Add 1, true
    .NumberStyle = 1
    .IncludeChapterNumber = True
    .HeadingLevelForChapter = 0
    .ChapterPageSeparator = 4
End With
'-------------------------------------------------------------------------------------------------------------------                                                                                                                                                                                                                                                                                                                               как сделать нумерацию в ворде
 
' Вставляем заданный текст во второй документ
For i=0 to 40
     With oRange2
                 .Text = MyText & MyText & MyText & MyText & MyText & MyText & MyText
                 .EndOf
                 .InsertParagraph()
                 .EndOf
     End With
Next
 
'-------------------------------------------------------------------------------------------------------------------
' Формируем нумерацию страниц в ворде вместе с заголовками для первого документа
'-------------------------------------------------------------------------------------------------------------------
With oDoc(2).Sections(1).Headers(1).PageNumbers
    .ShowFirstPageNumber = true
    .RestartNumberingAtSection = true
    .NumberStyle = 57
    .Add 0, true
    .StartingNumber = 5
End With

Пример программного кода на языке JSCRIPT:

// ----------------------------------------------------------------------------
// Коллекция PageNumbers и объекты PageNumber
// Нумерация в Word
// PageNumbers.js
// ----------------------------------------------------------------------------
var oWord1, oDoc1, i, MyText1, oRange1, oRange2;
 
oWord1 = WScript.CreateObject("Word.Application");
oDoc1 = oWord1.Documents;
oDoc1.Add();
oDoc1.Add();
oWord1.Visible = true;
oRange1 = oDoc1(1).Range();                           
oRange2 = oDoc1(2).Range();
 
MyText1 = "Нумерация в ворде. ";
 
// Вставляем 6 страниц в первый документ
for (i=0; i<=6; i++){
     with(oRange1){
                 InsertParagraph();
                 EndOf();
                 InsertBreak();
     }
}
 
//-------------------------------------------------------------------------------------------------------------------
// Формируем нумерацию страниц в Word вместе с заголовками для первого документа
//-------------------------------------------------------------------------------------------------------------------
oDoc1(1).Content.Style = -2;
oDoc1(1).Content.ListFormat.ApplyListTemplate (oWord1.ListGalleries(3).ListTemplates(7));
 
with (oDoc1(1).Sections(1).Headers(1).PageNumbers){
    Add(1, true);
    NumberStyle = 1;
    IncludeChapterNumber = true;
    HeadingLevelForChapter = 0;
    ChapterPageSeparator = 4;
}
//-------------------------------------------------------------------------------------------------------------------                                                                                                                                                                                                                                                                                                      как сделать нумерацию в ворде
 
// Вставляем заданный текст во второй документ
for (i=0; i<=40; i++){
     with(oRange2){
                 Text = MyText1 + MyText1 + MyText1 + MyText1 + MyText1 + MyText1 + MyText1;
                 EndOf();
                 InsertParagraph();
                 EndOf();
     }
}
 
//-------------------------------------------------------------------------------------------------------------------
// Формируем нумерацию страниц в ворде вместе с заголовками для первого документа
//-------------------------------------------------------------------------------------------------------------------
with (oDoc1(2).Sections(1).Headers(1).PageNumbers){
    ShowFirstPageNumber = true;
    RestartNumberingAtSection = true;
    NumberStyle = 57;
    Add(0, true);
    StartingNumber = 5;
}

В данных примерах происходит создание двух документов, для каждого документа создается ссылка на класс Range (переменные oRange1 и oRange2). Это нужно для того, что бы мы смогли добавить текст или страницы в нужный документ. Далее происходит нумерация страниц в Word для первого и второго документа. В одном случаем мы связываем нумерацию страниц в ворд со стилями и списками (в документ будут добавлены заголовки, а номера страниц будут с ними связаны). В другом случаем мы просто задаем стиль нумерация Word для всех страниц и определяем, что нумерация ворд должна начинаться с цифры 5.

Daniel


  • #1

It could be simple, but I can not find how to do it:

I need a code to get the page number of some range object, let me say, I
have a paragraph, and I want to know his location (page number) when printed.

Thanks, yours, Daniel
from Brazil

Advertisements

Jean-Guy Marcil


  • #2

Daniel was telling us:
Daniel nous racontait que :

It could be simple, but I can not find how to do it:

I need a code to get the page number of some range object, let me
say, I have a paragraph, and I want to know his location (page
number) when printed.

Did you see the post named : «How to get the current page number?» from 3
days ago?

In VBA you would use the Information property:

MsgBox Selection.Information(wdActiveEndPageNumber)
MsgBox Selection.Information(wdActiveEndAdjustedPageNumber)

where the first one gives you the absolute page count in the document and
the second the page number as defined in the Page Number formatting dialog
(Insert menu > Page Numbers…)

Salut!
_______________________________________
Jean-Guy Marcil — Word MVP
(e-mail address removed)
Word MVP site: http://www.word.mvps.org

m g


  • #3

I dont success know page number to some paragraph
any idia?

Danie wrote:

How to get page number with VBA in Word ?
12-Mar-07

It could be simple, but I can not find how to do it

I need a code to get the page number of some range object, let me say, I
have a paragraph, and I want to know his location (page number) when printed

Thanks, yours, Danie
from Brazil

EggHeadCafe — Software Developer Portal of Choice
Excel Conditional Hiding Without VBA
http://www.eggheadcafe.com/tutorial…15-b0106033e45c/excel-conditional-hiding.aspx

Jay Freedman


  • #4

Let’s assume you have a Range object that points to the paragraph or
something inside the paragraph (a bookmark, a field, a table, etc.), and
assume that Range object is named MyRange. Then the *absolute* page number
(simply counting pages from the start of the document, regardless of any
page numbering restarts in intervening sections) of the end of the paragraph
is

MyRange.Information(wdActiveEndPageNumber)

while the *adjusted* page number (taking into account page numbering
restarts, what would show if you put a {PAGE} field there) of the end of the
paragraph is

MyRange.Information(wdActiveEndAdjustedPageNumber)

There’s an additional wrinkle if you’re dealing with a selection made by the
user; if the selection was made by starting at the end of the paragraph and
selecting toward the beginning, and if the selection crosses a page
boundary, then the page number you get from the code above will be the page
that contains the beginning of the range (which is the «active» end).


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

Advertisements

Dale Fye


  • #5

Jay,

I was just about to ask an almost identical question, except focusing on a
document that I am buiding from scratch. Ended up using :

wdDoc.ActiveDocument.Selection.Information(wdActiveEndPageNumber) to get
what I needed.

I am devoping an Access 2013 app for a client that uses VBA and mail merge from with the access app to create word documents as output.  There will be many word documents created, one for each selected customer.

Eventually, these documents will be printed and mailed to the customers with the customers being responsible for postage fees.  The size of the documents will vary based on the amount of information being reported to the customer.  I need to determine the number of pages in the created word document so I can calculate the postage charges.

Is there some way to do this using VBA?  I will know the name and location of the created document.

It would be best if I can determine the number of pages as the document is being created.  I include the code I am using below.  Is there somewhere in that code that I could determine the number of pages in the document being created?

Here is an example of code I am using:

Public Sub CreateMailMerge_EE3_wPDF()

'open the mergedoc
        'late binding for version compatibility
        ''Dim oApp As Object
        ''Dim MlMrge As Object
        
        'Word constants (already defined if early binding)
        Const wdDefaultFirstRecord = 1
        Const wdDefaultLastRecord = -16
        Const wdSendToNewDocument = 0
        Const wdDoNotSaveChanges = 0
        
        'Early binding for easier development
        Dim oApp As Word.Application
        Dim MlMrge As Word.MailMerge
        Dim mmdoc As Word.Document
        Dim docResult As Word.Document
        
        '
        Dim strOutputFolder As String
        Dim strMailMergeMainDocument As String
        Dim strDatabase As String
        Dim bNewWordApp As Boolean
        Dim rec As Long
        Dim strCustID As String
        
        'strMailMergeMainDocument = "C:My DocumentsAccess_DatabasesJordanDelinqMailMergeTestDoc.docx"
        'strDatabase = "C:My DocumentsAccess_DatabasesJordanDelinqMailTestData.accdb"
        
        'strMailMergeMainDocument = "I:Allworkee28717544Customer.docx"
        strMailMergeMainDocument = "C:My DocumentsAccess_DatabasesJordanDelinqMailMergeTestDoc.docx"
        
        'strDatabase = "S:AllworkFreeoladb1.mdb"
        strDatabase = "C:My DocumentsAccess_DatabasesJordanDelinqMailTestData.accdb"
        
        'strOutputFolder = "I:Allworkee28717544"
        strOutputFolder = "C:My DocumentsAccess_DatabasesJordanDelinq"
        
        'try to avoid multiple instance of the Word application"
        On Error Resume Next 'temporarily supress error checking
            Set oApp = GetObject(, "Word.Application")
        On Error GoTo 0 'resume error checking
        If oApp Is Nothing Then
            Set oApp = CreateObject(Class:="Word.Application")
            bNewWordApp = True
        End If
        
        oApp.Visible = True
        
        'this will open a new document based on the path as a template.  Excellent
        'but will only open it as a mail merge if the original is a mailmerge document
        Set mmdoc = oApp.Documents.Add(strMailMergeMainDocument)
        ' so start a merge
        Set MlMrge = mmdoc.MailMerge
        With MlMrge
            'do the merge, get the datasource -- and be tricky if the Access app is opened exclusively!
            '
            ' Original //////////////////////////////////////////////
            '
            .OpenDataSource Name:=strDatabase, _
            LinkToSource:=True, AddtoRecentFiles:=False, _
            Connection:="TABLE [tblNameFile]", _
            SQLStatement:="SELECT * FROM [tblNameFile]"
             'do you want merge to email instead
            .Destination = 0 'wdSendToNewDocument
            .SuppressBlankLines = True
            For rec = 1 To .DataSource.RecordCount
                With .DataSource
                
                    .FirstRecord = rec
                    .LastRecord = rec
                    .ActiveRecord = rec
                    strCustID = .DataFields("LastName").Value

                End With
                
                .Execute (False) 'execute and don't stop for errors -- list them in a new Word document, if any.
                
                Set docResult = oApp.ActiveDocument
                'docResult.SaveAs strOutputFolder & "" & strCustID & ".docx"
                 docResult.SaveAs strOutputFolder & "" & strCustID & ".docx", wdFormatDocumentDefault
                docResult.SaveAs FileName:=strOutputFolder & "" & strCustID & ".pdf", FileFormat:=WdSaveFormat.wdFormatPDF
                docResult.Close wdDoNotSaveChanges
            Next rec
        End With
    mmdoc.Close wdDoNotSaveChanges
    If bNewWordApp Then
        oApp.Quit
    End If
End Sub

Open in new window

Like this post? Please share to your friends:
  • Word using prefix semi
  • Word vba if не равно
  • Word using prefix mis
  • Word vba if error
  • Word using prefix dis