2
votes

I want to count the number of pages in Word documents using Excel VBA but some files can't be opened, with

"Error 5180 Word Cannot open document template".

Function PageWord(FullFile_Name As Variant, PF As Long)
Dim objWord As Object
Dim objDoc As Object

On Error Resume Next
Set objWord = CreateObject("Word.Application")
objWord.Visible = False


Set objDoc = objWord.Documents.Open(filename:="" & FullFile_Name & "", ReadOnly:=False)
objDoc.Repaginate


PageWord = objDoc.BuiltinDocumentProperties(14)   'Pages
Debug.Print PageWord & "-" & FullFile_Name


objWord.Quit (False)
End Function  

How to open these files or is there another way to get the page counts?

1

1 Answers

0
votes

It's possible to get the page count without opening the file, using Microsoft Developer Support OLE File Property Reader 2.1

http://www.microsoft.com/en-us/download/details.aspx?id=8422

Once installed, you can instantiate an instance of the property reader and find the page count like this:

Function PageWord(FullFile_Path as string)

    Dim dso As Object

    Set dso = CreateObject("DSOFile.OleDocumentProperties") 
    dso.Open (FullFile_Path) 
    PageWord = dso.SummaryProperties.PageCount
    dso.Close 

    Debug.Print PageWord & "-" & FullFile_Path

End Function

If you instantiate the dso object outside of the function and pass it along with the path of the file (or if you scope it to be accessible to the function), you won't need to open and close a bunch of dso objects, either.