|
以下代码使用shell.application获取word文档页数,可能会不准
可靠的方式要区分新旧文件格式:
对旧文件格式,doc等,要使用复合文档技术
用复合文档API StgOpenStorage和IPropertySetStorage读Page Count属性
对新文件格式,docx等,要使用xml读取技术
Open XML SDK打开文件之后读ExtendedFilePropertiesPart.Properties.Pages属性
但是实际对于新文件格式还可以直接解压获取文件中的app.xml文件,内有<Pages>xx</Pages>标签 - Function GetPagesCount(ByVal flPath As String) As Integer
- Dim fso As Object, fl As Object, shl As Object
- Dim fdPath$, flName$, i&, shfd As Object
- Set fso = CreateObject("Scripting.FileSystemObject")
- Set fl = fso.GetFile(flPath)
- fdPath = fl.ParentFolder.Path
- flName = fl.Name
- Set shl = CreateObject("Shell.Application")
- Set shfd = shl.NameSpace(fdPath)
- For i = 0 To 300
- If Left(shfd.GetDetailsOf(0, i), 1) = "页" Then 'XP中为"页数",Win7中为"页码范围",所有直接查找"页"
- GetPagesCount = shfd.GetDetailsOf(shfd.Items.Item(flName), i)
- Exit Function
- End If
- Next i
- End Function
- Sub 遍历获取页数()
- Application.ScreenUpdating = False
- Dim fso As Object, objFolder As Object, ws As Object, Ext$, srcfolder$, dstfolder$, arr, aMsg
- Dim aDic As Object, wdApp As Word.Application, strTemp$, aNum&, pgCount&, aPage&
- Set wdApp = CreateObject("Word.Application")
- Set fso = CreateObject("Scripting.FileSystemObject")
- Set ws = CreateObject("WScript.Shell")
- Set aDic = CreateObject("Scripting.Dictionary")
- srcfolder = "C:\Documents and Settings\Administrator\桌面\新建文件夹"
- ws.Run Environ$("comspec") & " /c dir " & Chr(34) & srcfolder & "\*.doc" & Chr(34) & " /s /b /a:-d > C:\tmpDoc.txt", 0, True '遍历获取Word文件,并列表到临时文件
- aNum = FreeFile()
- Open "C:\tmpDoc.txt" For Input As #aNum
- arr = Split(StrConv(InputB(LOF(aNum), aNum), vbUnicode), vbCrLf) '将遍历结果从文件读取到数组中
- Close #1
- ws.Run Environ$("comspec") & " /c del /q /s " & Chr(34) & "C:\tmpDoc.txt" & Chr(34), 0, True '删除临时文件
- For i = LBound(arr) To UBound(arr) - 1
- If Left(fso.getfilename(arr(i)), 2) <> "~$" Then '排除临时文件
- aPage = GetPagesCount(arr(i))
- pgCount = pgCount + aPage
- strTemp = strTemp & aPage & vbTab & arr(i) & Chr(13)
- End If
- Next i
- aNum = FreeFile()
- Open "C:\PageCount.txt" For Output As #aNum
- Print #aNum, strTemp
- Close #aNum
- Set fso = Nothing '销毁fso对象,释放内存
- Set ws = Nothing '销毁Shell对象,释放内存
- MsgBox "统计总页数完毕,总页数:" & pgCount & vbCrLf & "C:\PageCount.txt为统计结果"
- Application.ScreenUpdating = True
- End Sub
复制代码 |
评分
-
1
查看全部评分
-
|