想要显示一个文件夹中有多少个PDF文件

时间:2018-07-13 15:14:13

标签: vba excel-vba

Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim ws As Worksheet
Dim lngFileCount As Long

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = ActiveSheet

Dim folderpath
folderpath = InputBox("N:\Files", "Folder Path")
Set objFolder = objFSO.GetFolder(folderpath)
ws.Cells(1, 1).Value = "The files found in " & objFolder.Name & " are:"

For Each objFile In objFolder.Files
    If UCase$(Right$(objFile.Name, 4)) = ".PDF" Then
        ws.Cells(ws.UsedRange.Rows.Count + 1, 1).Value = Replace$(UCase$(objFile.Name), ".PDF", "")
        Z = Z + 1
        MsgBox objFolder.Count.Z & ": The total number file in folder: "
    End If
Next

If Z = 0 Then
       MsgBox "No PDF Files found"
End If

Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing

End Sub

2 个答案:

答案 0 :(得分:1)

尝试一下:

Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim ws As Worksheet
Dim lngFileCount As Long
Dim Z as Long

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = ActiveSheet

Dim folderpath As String
folderpath = InputBox("N:\Files", "Folder Path")
Set objFolder = objFSO.GetFolder(folderpath)
ws.Cells(1, 1).Value = "The files found in " & objFolder.Name & " are:"

For Each objFile In objFolder.Files
    If UCase$(Right$(objFile.Name, 4)) = ".PDF" Then
        ws.Cells(ws.UsedRange.Rows.Count + 1, 1).Value = Replace$(UCase$(objFile.Name), ".PDF", "")
    Z = Z + 1

    End If
Next
If Z = 0 Then

    MsgBox "No PDF Files found"

Else

    MsgBox "The total number of files in folder: " & Z

End If
Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing

我将MsgBox移到了循环的外面,所以您只看到一次它的总数。

属性objFolder.Count.Z不存在,您只需要变量Z,用于存储PDF文件的数量。

答案 1 :(得分:1)

使用以下功能获取文件数

Function numberOfFiles(ByVal dirName As String, ByVal mask As String) As Long
    On Error GoTo Catch

    Dim maskName As String
    maskName = dirName & mask

    With CreateObject("wscript.shell")
        numberOfFiles = UBound(Split(.exec("cmd /c Dir """ & maskName & """ /b/a").stdout.readall, vbCrLf)) - 1
    End With

    Exit Function

Catch:
    numberOfFiles = 0

End Function

进行测试
Sub testIt()
    Debug.Print numberOfFiles("D:\user\examples\", "*.pdf")
End Sub

您的代码更改为

Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim ws As Worksheet
Dim lngFileCount As Long
Dim Z As Long

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = ActiveSheet

Dim folderpath As String
folderpath = InputBox("N:\Files", "Folder Path")
Set objFolder = objFSO.GetFolder(folderpath)

ws.Cells(1, 1).Value = "The files found in " & objFolder.Name & " are:"

Z = numberOfFiles(folderpath, "*.PDF")

If Z = 0 Then
    MsgBox "No PDF Files found"
Else
    MsgBox "The total number of files in folder: " & Z
End If

Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing

,只需在其下面添加numberOfFiles函数。