how to read certain files in a directory in excel VBA

眉间皱痕 提交于 2020-01-03 03:14:35

问题


I want to read certain excel files from a directory and then open them in excel-2007 with VBA.

Here is an example:
directory: c:\temp
file pattern: is xxxxx0123.xls (xxxxx represents the file names).

I try to use Application.FileSearch, but it won't work in Excel 2007. Does any one have good suggestions?

Thanks in advance


回答1:


You can use DIR to find files matching your pattern, ie this code opens these files, grabs their path, and closes the files again

The code can be made recursive if you need to look in sub-folders

Sub GetFiles()
    Dim strFolder As String
    Dim strFileName As String
    Dim wb As Workbook
    strFolder = "C:\temp"
    strFileName = Dir(strFolder & "\*123.xls")
    Do While Len(strFileName) > 0
        Set wb = Workbooks.Open(strFileName)
        Debug.Print wb.FullName
        wb.Close False
        strFileName = Dir
    Loop
End Sub


来源:https://stackoverflow.com/questions/9202456/how-to-read-certain-files-in-a-directory-in-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!