这是我用于列出文件的过程:
Function GetFileList(pDirPath As String) As Variant
On Error GoTo GetFileList_err
' Local constants / variables
Const cProcName = "GetFileList"
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim c As Double ' upper bound for file name array
Dim i As Double ' iterator for file name array
Dim vFileList() As String ' array for file names
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(pDirPath)
c = objFolder.Files.Count
i = 0
ReDim vFileList(1 To c) ' set bounds on file array now we know count
'Loop through the Files collection
For Each objFile In objFolder.Files
'Debug.Print objFile.Name
i = i + 1
vFileList(i) = objFile.Name
Next
'Clean up!
Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
GetFileList = vFileList
GetFileList_exit:
Exit Function
GetFileList_err:
Debug.Print "Error in ", cProcName, " Err no: ", Err.Number, vbCrLf, "Err Description: ", Err.Description
Resume Next
End Function
Sub PrintFileList(pDirPath As String, _
Optional pPrintToSheet = False, _
Optional pStartCellAddr = "$A$1", _
Optional pCheckCondition = False, _
Optional pFileNameContains)
On Error GoTo PrintFileList_err
' Local constants / variables
Const cProcName = "PrintFileList"
Dim vFileList() As String ' array for file names
Dim i As Integer ' iterator for file name array
Dim j As Integer ' match counter
Dim c As String
vFileList = GetFileList(pDirPath)
c = pStartCellAddr
j = 0
For i = LBound(vFileList) To UBound(vFileList)
If pPrintToSheet Then
If pCheckCondition Then
' if pFileNameContains not in filename go to next iteration of loop
If InStr(1, vFileList(i), pFileNameContains, vbTextCompare) = 0 Then
GoTo EndLoop
End If
End If
Range(c).Offset(j, 0).Value = vFileList(i)
j = j + 1
End If
'Debug.Print vFileList(i)
i = i + 1
EndLoop:
Next
PrintFileList_exit:
Exit Sub
PrintFileList_err:
Debug.Print "Error in ", cProcName, vbCrLf, "Err no: ", Err.Number, _
vbCrLf, "Err Description: ", Err.Description
Resume Next
End Sub
该函数仅供内部使用,您调用该过程。这是一个示例调用(在这种情况下,使用 userprofile windows 环境变量作为路径而不是硬编码路径):
call PrintFileList(environ("userprofile"), True, "$A$1", True, ".pdf")