Public Function TreeSearch(ByVal sPath As String, ByVal sFileSpec As String, sFiles() As String) As Long
On Error Resume Next
Static Files As Long '文件数目
Dim sDir As String
Dim sSubDirs() As String '存放子目录名称
Dim Index As Long
If Right(sPath, 1) <> "\" Then sPath = sPath & "\"
sDir = Dir(sPath & sFileSpec)
'获得当前目录下文件名和数目
Do While Len(sDir)
Files = Files + 1
ReDim Preserve sFiles(1 To Files)
sFiles(Files) = sPath & sDir
sDir = Dir
Loop
'获得当前目录下的子目录名称
Index = 0
sDir = Dir(sPath & "*.*", 16)
Do While Len(sDir)
If Left(sDir, 1) <> "." Then 'skip.and..
'找出子目录名
If GetAttr(sPath & sDir) And vbDirectory Then
Index = Index + 1
'保存子目录名
ReDim Preserve sSubDirs(1 To Index)
sSubDirs(Index) = sPath & sDir & "\"
End If
End If
sDir = Dir
Loop
For Index = 1 To Index
'查找每一个子目录下文件,这里利用了递归
Call TreeSearch(sSubDirs(Index), sFileSpec, sFiles())
Next Index
TreeSearch = Files
End Function
这是函数,不过现在他在ListBox中是显示完整的路径,我只想让它显示最后一个目录加文件名。
现在是:D:\123\345\567\000.txt
我只想让它显示:567\000.txt 在ListBox中。
UBound 缺少数组??
追答你的机器没有F盘,或F盘下没有EXE文件
追问可是我要遍历的目录是一个变量。
这个变量在程序运行的时候,才会得到路径。
把上面的"f:\"、"*.exe"分别改成你的目录变量和文件类型即可:
Private Sub Command1_Click()
Dim arr() As String
If TreeSearch(你的目录变量, 你要查询的文件类型, arr) = 0 Then Exit Sub
For i = LBound(arr) To UBound(arr)
arr1 = Split(arr(i), "\")
List1.AddItem arr1(UBound(arr1) - 1) & "\" & arr1(UBound(arr1))
Next
End Sub
T.T 还是不行,缺少数组。
追答那是你的其他代码的问题
Private Sub Command1_Click()
Dim arr() As String
If TreeSearch("D:\", "*.txt", arr) = 0 Then Exit Sub
For i = LBound(arr) To UBound(arr)
arr1 = Split(arr(i), "\")
List1.AddItem arr1(UBound(arr1) - 1) & "\" & arr1(UBound(arr1))
Next
End Sub
你看一下语句的构成就会发现,那段代码是经过VB测试过的。
T.T 失败! 说 i 未定义。。。
追答这是强制定义变量的问题:
Dim arr() As String改成:
Dim arr() As String,i as integer
或加一行:
dim i as integer