Skip to content

Instantly share code, notes, and snippets.

@chenzx
Created January 7, 2013 09:28
Show Gist options
  • Save chenzx/4473672 to your computer and use it in GitHub Desktop.
Save chenzx/4473672 to your computer and use it in GitHub Desktop.
VBScript to automate Word to do chinese words statistics, not very robust.
Dim objWord ' As Word.Application
Dim objDoc ' As Word.Document
Dim fso, fResult
Dim objShell
strResultFilePath = "c:/wordsStat.txt"
'On Error Goto CleanObjs: 'WScript不支持goto label语法?
On Error Resume Next
Set objShell = CreateObject("Wscript.Shell")
Set objWord = WScript.CreateObject("Word.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFolder = fso.GetFolder(".")
Function GetDocFileWordsCount(objWord, strFilePath)
Set objDoc = objWord.Documents.Open(strFilePath)
wordsCount = objDoc.ComputeStatistics(wdStatisticWords, True) '包含脚注
objDoc.Close
GetDocFileWordsCount = wordsCount
End Function
'枚举当前路径下的*.doc文件:
strAllDocsStatResult = ""
For Each objFile In objFolder.Files
strFilePath = objFile.Path
strFileName = objFile.Name
If LCase(Mid(strFilePath, Len(strFilePath)-2, 3))="doc" Then 'VB的字符串下标从1开始?
wordsCount = GetDocFileWordsCount(objWord, strFilePath)
strAllDocsStatResult = strAllDocsStatResult & "" & strFilePath & ": (" & strFileName & ")总字数为" & wordsCount & vbCrLf
End If
Next
'WScript.Echo( "总字数为" & wordsCount )
If fso.FileExists(strResultFilePath) Then
fso.DeleteFile strResultFilePath, True
End If
Set fResult = fso.OpenTextFile(strResultFilePath, 2, True)
fResult.Write( strAllDocsStatResult )
fResult.Close
objShell.Run "notepad.exe " & strResultFilePath
'CleanObjs:
On Error Resume Next
Set objDoc = Nothing
objWord.Quit False '显式退出,否则进程管理器里会出现一个多余的winword.exe
Set objWord = Nothing
Set fso = Nothing
Set objShell = Nothing
WScript.quit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment