0

我遇到了许多 VBA 的字数统计宏,但我不知道如何遍历目录中的每个“doc”文件并生成每个文件中字数的报告。我们如何生成这样的报告?

4

1 回答 1

1

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
于 2013-03-31T20:20:38.957 回答