计算目录中每个文档中的单词

时间:2013-03-31 17:46:55

标签: vba ms-word

我遇到了许多用于VBA的字数统计宏但我无法弄清楚如何迭代目录中的每个“doc”文件并生成每个文件中单词数量的报告。我们怎样才能生成这样的报告?

1 个答案:

答案 0 :(得分:0)

GSerg得到的是,您需要遍历包含文档的文件夹,打开它们,并获得字数。

据我所知,如果不打开文档(通过VBA),如果没有安装额外的库,则无法获得单词计数,如下所述: http://support.microsoft.com/kb/224351/en-us

但是我不会这样做,因为根据我的经验,文件属性中的计数是不准确的,因为我认为他们使用了具有本文所述问题的Words属性: http://support.microsoft.com/kb/291447

因此,如果您想获得准确的计数,我相信唯一的方法是遍历文件并打开它们,就像这样。请记住将路径名称更改为真实路径:

Sub ListWordCount()
    'In the Visual Basic Editor,
    'go to Tools -> References and check the box for
    'Microsoft Scripting Runtime to access the
    'filesystem object.

    Dim fso As Scripting.FileSystemObject
    Dim fol As Scripting.Folder
    Dim cfil As Variant
    Dim fil_1 As Scripting.File

    Dim s As String

    'The FSO isn't the fastest object in existence
    'and much slower than using the Windows API (or its
    'VB.Net namesake for that matter) but it's convenient
    'and easy to use.
    Set fso = New FileSystemObject
    Set fol = fso.GetFolder("InsertYourPathHere")
    Set cfil = fol.Files

    'Helps it run a bit faster...
    Application.ScreenUpdating = False

    For Each fil_1 In cfil

        Select Case fil_1.Type
            'Add any other types that you want to check for
            Case "Microsoft Word 97 - 2003 Document", _
             "Microsoft Word Document"

            Documents.Open FileName:=fil_1.Path

            Debug.Print fil_1.Name & vbTab & _
             ActiveDocument.Range.ComputeStatistics(wdStatisticWords) _
             & " words."

            Documents.Close savechanges:=False

        End Select

    Next

ExitPoint:
On Error Resume Next
Set fil_1 = Nothing
Set cfil = Nothing
Set fol = Nothing
Set fso = Nothing
Application.ScreenUpdating = True
Application.ScreenRefresh
On Error GoTo 0

Exit Sub

ErrorHandler:

MsgBox Err.Number & vbCr & Err.Description

Resume ExitPoint

End Sub