Excel精英培训网

 找回密码
 注册
数据透视表40+个常用小技巧,让你一次学会!
查看: 3580|回复: 3

VBA入门新手请教如何使用Dir替换Application.Filesearch

[复制链接]
发表于 2019-6-17 17:24 | 显示全部楼层 |阅读模式
2学分
我刚开始学VBA,写了一个顺序搜索excel文件的代码,但是提示我445,我搜了一下发现现在的excel不支持Application.Filesearch了,并且我不知道怎么使用Dir对搜索出来的文件进行排序,想请大佬帮忙改一下,能达到通过单击单元格内的内容,以该内容为关键词,搜索指定文件夹中的excel文件,对搜索出来的文件进行排序和添加超链接的效果。我整了半天还是不会,求各位大佬能不吝赐教,万分感谢!!
代码如下所示:
Sub SearchFile()
   With Application.FileSearch
       .NewSearch
       .LookIn = "C:\Users"
       .SearchSubFolders = True
       .Filename = "*.xlsx"
       .Execute SortBy:=msoSortByLastModified, sortorder:=msoSortOrderDescending
       If .FoundFiles.Count > 0 Then
          For i = 1 To .FoundFiles.Count
              Cells(i, 1).Value = .FoundFiles()
          Next
       End If
    End With
End Sub


excel精英培训的微信平台,每天都会发送excel学习教程和资料。扫一扫明天就可以收到新教程
匿名  发表于 2019-6-20 10:15
请参考


Sub test()
    With Application.FileDialog(msoFileDialogFolderPicker)
         MsgBox "请选择文件夹", 48, "温馨提示!"
        If .Show = -1 Then '选择文件夹
            mp = .SelectedItems(1) & "\" '您选择文件夹路径
        End If
    End With
    mf = Dir(mp & "*.xlsx")
    Set sht = ThisWorkbook.Sheets(1)
    sht.Range("a1:a10000").Clear
    Do
        i = i + 1
        Cells(i, 1).Value = mf
        sht.Hyperlinks.Add anchor:=sht.Cells(i, 1), Address:=mp & mf, TextToDisplay:=Left(mf, Len(mf) - 5)
        mf = Dir
    Loop While mf <> ""
    MsgBox "完毕!", 48, "温馨提示!"
    sht.Activate
    ThisWorkbook.Save
End Sub
回复

使用道具

匿名  发表于 2019-6-20 10:15
请参考


Sub test()
    With Application.FileDialog(msoFileDialogFolderPicker)
         MsgBox "请选择文件夹", 48, "温馨提示!"
        If .Show = -1 Then '选择文件夹
            mp = .SelectedItems(1) & "\" '您选择文件夹路径
        End If
    End With
    mf = Dir(mp & "*.xlsx")
    Set sht = ThisWorkbook.Sheets(1)
    sht.Range("a1:a10000").Clear
    Do
        i = i + 1
        Cells(i, 1).Value = mf
        sht.Hyperlinks.Add anchor:=sht.Cells(i, 1), Address:=mp & mf, TextToDisplay:=Left(mf, Len(mf) - 5)
        mf = Dir
    Loop While mf <> ""
    MsgBox "完毕!", 48, "温馨提示!"
    sht.Activate
    ThisWorkbook.Save
End Sub
回复

使用道具

 楼主| 发表于 2019-6-21 13:01 | 显示全部楼层

哇谢谢大佬!我想问一下,有没有办法不选择文件夹,用类似Lookin这样的语句提前编入目标文件夹呢?
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|Excel精英培训 ( 豫ICP备11015029号 )

GMT+8, 2024-3-29 06:33 , Processed in 0.400174 second(s), 8 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表