Private Sub Command1_Click()
Dim fs, f, f1, fc, s,s1
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder("d:\d") '文件夹路径名称
Set fc = f.Files
For Each f1 In fc
s=s+1
Next
Set fc = f.SubFolders
For Each f1 In fc
s1 = s1+1
fs.DeleteFolder "d:\d\" & f1.Name
Next
msgbox s & “个文件” & S1 &“个文件夹"
End Sub
Option Explicit
Dim fso As FileSystemObject
Private Function FileCountOFFolder() as long
Set fso = New FileSystemObject
Dim f As Files
Set f = fso.GetFolder("c:\Output").Files
MFileCountOFFolder= f.Count
End Function
学习......
Function FindDirectory(RootPath As
String, Mydirectory() As String)
Dim intResult, I, intFind As Integer
‘首先查找根目录下的所有子目录
MyPath = "c:\" ' 指定路径c:\。
MyName = Dir(MyPath, vbDirectory) ' 找寻第一项。
intResult = 1
ReDim Mydirectory(intResult) ‘初始化动态数组
Do While MyName < > "" ' 开始循环。
' 跳过当前的目录及上层目录。
If MyName < > "." And MyName < > ".." Then
' 使用位比较来确定 MyName 代表一目录。
If (GetAttr(MyPath & MyName)
And vbDirectory) = vbDirectory Then
' 如果它是一个目录,将其名称存储在一个数组里。
Mydirectory(intResult) = MyPath & MyName
intResult = intResult + 1
ReDim Preserve Mydirectory(intResult)
‘分配动态数组实际的元素个数,并保留数组中的数据
End If
End If
MyName = Dir ' 查找下一个目录。
Loop
‘在所有目录里分别查找文件是否存在。
For I = 1 To UBound(Mydirectory)-1
MyFile = Mydirectory(I) & "\win.ini"
intFind = Len(Dir(MyFile))
If intFind < > 0 Then MsgBox "找到文件" &
Dir(MyFile) & "在:" & Mydirectory(I)
Next I
End Function
---- 该函数的思路很清晰:先遍历根目录下所有的子目录,然后在每个子目录里查找文件。该函数有一个缺陷:只能查找根目录下的一级子目录,无法遍及整个硬盘。如果要遍及整个硬盘,还需要额外的编码,这里不再多述。
Declare
Public Declare Function SearchTreeForFile Lib
"imagehlp.dll" (ByVal lpRoothPath As String,
ByVal lpInputName As String,
ByVal lpOutputName As String) As Long
---- 下面为sysFileFind函数的编码:
Public Function sysFileFind
(ByVal WhichRootPath As String,
ByVal WhichFileName As String) As String
Dim iNull As Integer
Dim lResult As Long
Dim sBuffer As String
On Error GoTo L_FILEFINDERROR
sBuffer = String$(1024, 0)
'查找文件
lResult = SearchTreeForFile
(WhichRootPath, WhichFileName, sBuffer)
'如果文件找到,将返回字符串后续的空格删除
'否则返回一个空字符串
If lResult Then
iNull = InStr(sBuffer, vbNullChar)
If Not iNull Then
sBuffer = Left$(sBuffer, iNull - 1)
End If
sysFileFind = sBuffer
Else
sysFileFind = ""
End If
Exit Function
L_FILEFINDERROR:
MsgBox "查找文件过程中遇到错误!",
vbInformation, "查找文件错误"
sysFileFind = Format(Err.Number)
& " - " & Err.Description
End Function
---- 该函数可以很快遍历整个硬盘,从而查找到我们所需的文件。
Option Explicit
Dim fso As FileSystemObject
Private Function FileCountOFFolder() as long
Set fso = New FileSystemObject
Dim f As Files
Set f = fso.GetFolder("c:\Output").Files
MFileCountOFFolder= f.Count
End Function