微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VB用TreView罗列出指定目录下的所有目录及文件

Public Function SearchFiles(Path As String,FileType As String)     '历遍指定路径中的文件
    Dim Files()  As String '文件路径
    Dim Folder() As String '文件夹路径
    Dim 父() As String
    Dim a,b As Long
    Dim sPath As String
    Dim Nodeindex As Node
    On Error Resume Next
    If Right(Path,1) <> "\" Then Path = Path & "\"
    sPath = Dir(Path & FileType) '查找第一个文件
    do while Len(sPath) '循环到没有文件为止
        If Path = Text1.Text Then
            Set Nodeindex = TreeView1.Nodes.Add(,sPath,sPath)
        Else
            父 = Split(Path,"\")
            Set Nodeindex = TreeView1.Nodes.Add(父(UBound(Split(Path,"\")) - 1),tvwChild,sPath)
        End If
        Nodeindex.sorted = True
        sPath = Dir '查找下一个文件
        DoEvents '让出控制权
    Loop
    i = 0
    sPath = Dir(Path & "\",vbDirectory) '查找第一个文件do while Len(sPath) '循环到没有文件夹为止
        If Left(sPath,1) <> "." Then '为了防止重复查找
            If GetAttr(Path & "" & sPath) And vbDirectory Then '如果是文件夹则。。。。。。
                a = a + 1
                ReDim Preserve Folder(1 To a)
                Folder(a) = Path & sPath & "\" '将目录和文件名称组合形成新的目录,并存放到数组中
                'Print Path
                If Path = Text1.Text Then
                    Set Nodeindex = TreeView1.Nodes.Add(,sPath)
                Else
                    父 = Split(Path,"\")
                    Set Nodeindex = TreeView1.Nodes.Add(父(UBound(Split(Path,sPath)
                End If
                Nodeindex.sorted = True
            End If
        End If
        sPath = Dir '查找下一个文件夹
        DoEvents '让出控制权
    Loop
    For b = 1 To a '使用递归方法,遍历所有目录
        SearchFiles Folder(b),FileType
    Next
End Function
 
Private Sub Command1_Click()
    SearchFiles Text1.Text,"*.*"    'Text1.Text为指定目录路径比如"D:"
End Sub

原文地址:https://www.jb51.cc/vb/258976.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐