这个例子是查找C盘中的所有目录及文件,主要用到的就是dir()函数。根据这个实例更加明白dir()函数的应用。
设计过程:
Ⅰ、设计思路:
用dir()函数来查找C盘,首先查找C盘的根目录的文件夹,在分别查找各个文件夹里面的文件夹,依次进行查找。
Ⅱ、设计界面
用一个列表框来显示C盘中的所有目录,用另一个列表框显示C盘中所有的文件,并且用一个命令按钮来控制查找开始。
Ⅲ、功能代码
Private Sub Command1_Click()
Dim i As Long
Dim RootPath As String
Dim FindDir As String
Dim FindFiles As String
Dim DirName() As String
Dim DirCount As Long
Command1.Enabled = False
DoEvents
DirCount = 1
ReDim DirName(1 To DirCount) As String
DirName(1) = "C:"
List1.AddItem "C:/"
Dim CurIndex As Long
CurIndex = 1
Do While (CurIndex <= DirCount)
RootPath = DirName(CurIndex) & "/"
FindDir = Dir(RootPath, vbDirectory)
Do While (FindDir <> "")
If ((FindDir <> ".") And (FindDir <> "..")) Then
On Error Resume Next
If ((GetAttr(RootPath & FindDir) And vbDirectory) = vbDirectory) Then
DirCount = DirCount + 1
ReDim Preserve DirName(1 To DirCount) As String
DirName(DirCount) = RootPath & FindDir
List1.AddItem RootPath & FindDir
End If
End If
FindDir = Dir
Loop
DoEvents
CurIndex = CurIndex + 1
Loop
For i = 1 To DirCount
RootPath = DirName(i) & "/"
FindFiles = Dir(RootPath, vbArchive)
Do While (FindFiles <> "")
List2.AddItem RootPath & FindFiles
FindFiles = Dir
Loop
DoEvents
Next
MsgBox "ok!查找完毕!"
Command1.Enabled = TrueEnd Sub