10、生成文件夹下所有文件的目录

Sub search1()'定目录,返回文件目录树
    On Error GoTo 100
    Dim wsh As Object, mypath As String, ar, i&, br
    mypath = CreateObject("shell.application").BrowseForFolder(0, "请选择要搜索的文件夹", 0).Items.Item.Path    '在此指定目录
    Set wsh = CreateObject("wscript.shell")
    mypath = wsh.exec("cmd /c tree /f " & Chr(34) & mypath & Chr(34)).StdOut.ReadAll
    mypath = Left(mypath, Len(mypath) - 1)
    ar = Split(mypath, vbCrLf)
    ReDim br(1 To UBound(ar) + 1, 1 To 1)
    For i = 0 To UBound(ar)
        br(i + 1, 1) = ar(i)
    Next
    
    Range("a1").Resize(UBound(br)) = br
    Set wsh = Nothing
100:
End Sub

Sub search2()  '查找文件、文件夹,结果返回完整路径
    On Error GoTo 100
    Dim wsh As Object, mypath As String, ar, st$
    mypath = CreateObject("shell.application").BrowseForFolder(0, "请选择要搜索的文件夹", 0).Items.Item.Path    '在此指定目录
    st = InputBox("请输入要搜索的目标文件部分或全部名字。 比如:xls      如果“取消”就默认为全部文件。", _
         "文件名关键字", "xls")
    Set wsh = CreateObject("wscript.shell")
    mypath = wsh.exec("cmd /c dir /a /s /b /a-d " & Chr(34) & mypath & Chr(34)).StdOut.ReadAll
    mypath = Left(mypath, Len(mypath) - 1)
    ar = Split(mypath, vbCrLf)
    ar = Filter(ar, st)
    Set wsh = Nothing
    Cells.ClearContents
    Range("a1").Resize(UBound(ar) + 1) = Application.Transpose(ar)
    Hyperlinks.Add Anchor:=Application.Transpose(ar), Address:=Application.Transpose(ar)
100:
End Sub

'全盘查找指定文件
'以下代码单独放一个模块吧
 '原代码只适用VB7以前版本和Win32,加入PtrSafe后可适用VB7和Win64
Private Declare PtrSafe Function SearchTreeForFile Lib "ImageHlp.dll" (ByVal lpRoot As String, ByVal lpInPath As String, ByVal lpOutPath As String) As Long
Private Declare PtrSafe Function GetDriveType Lib "kernel32" Alias "GetDriveTypeA" (ByVal nDrive As String) As Long

Function SearchFile(ByVal Filename As String) As String
    Dim R As Long, i As Long, SearchPath As String
    For i = 0 To 10
    SearchPath = Chr$(i + 65) & ":\"
    If GetDriveType(SearchPath) = 3 Then
        SearchFile = String$(1024, 0)
        R = SearchTreeForFile(SearchPath, Filename, SearchFile)
        If R <> 0 Then SearchFile = Split(SearchFile, Chr(0))(0): Exit Function
        End If
    Next
    SearchFile = "未能找到文件!"
End Function

Sub FindFile()
    Dim F As String
    F = InputBox("请输入要查找的文件名称!", "提示", "示例:excel.exe")
    [a1] = SearchFile(F)
End Sub

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值