以下从MS网上找到的(原代码是在VB中运行,已改可在excel中运行,需要建立窗体,内命令按钮、标签 和 列表框 各一个,并引用microsoft scripting runtime),是用递归: Option Explicit Dim fso As New FileSystemObject Dim fld As Folder Private Function FindFile(ByVal sFol As String, sFile As String, _ nDirs As Long, nFiles As Long) As Currency Dim tFld As Folder, tFil As File, FileName As String On Error GoTo Catch Set fld = fso.GetFolder(sFol) FileName = Dir(fso.BuildPath(fld.Path, sFile), vbNormal Or _ vbHidden Or vbSystem Or vbReadOnly) While Len(FileName) <> 0 FindFile = FindFile + FileLen(fso.BuildPath(fld.Path, _ FileName)) nFiles = nFiles + 1 ListBox1.AddItem fso.BuildPath(fld.Path, FileName) ' Load ListBox FileName = Dir() ' Get next file DoEvents Wend Label1 = "Searching " & vbCrLf & fld.Path & "..." nDirs = nDirs + 1 If fld.SubFolders.Count > 0 Then For Each tFld In fld.SubFolders DoEvents FindFile = FindFile + FindFile(tFld.Path, sFile, nDirs, nFiles) Next End If Exit Function Catch: FileName = "" Resume Next End Function Private Sub CommandButton1_Click() Dim nDirs As Long, nFiles As Long, lSize As Currency Dim sDir As String, sSrchString As String sDir = InputBox("Type the directory that you want to search for", _ "FileSystemObjects example", "C:\") sSrchString = InputBox("Type the file name that you want to search for", _ "FileSystemObjects example", "vb.ini") Label1.Caption = "Searching " & vbCrLf & UCase(sDir) & "..." lSize = FindFile(sDir, sSrchString, nDirs, nFiles) MsgBox Str(nFiles) & " files found in" & Str(nDirs) & _ " directories", vbInformation MsgBox "Total Size = " & lSize & " bytes" End Sub |