vba 如何在excel VBA中读取目录中的某些文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9202456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to read certain files in a directory in excel VBA
提问by user1188125
I want to read certain excel files from a directory and then open them in excel-2007with VBA.
我想从目录中读取某些 excel 文件,然后使用 VBA在excel-2007 中打开它们。
Here is an example:
directory: c:\temp
file pattern: is xxxxx0123.xls
(xxxxx represents the file names).
下面是一个例子:
目录:c:\temp
文件模式:是xxxxx0123.xls
(xxxxx 代表文件名)。
I try to use Application.FileSearch
, but it won't work in Excel 2007. Does any one have good suggestions?
我尝试使用Application.FileSearch
,但它在 Excel 2007 中不起作用。有人有好的建议吗?
Thanks in advance
提前致谢
回答by brettdj
You can use DIR
to find files matching your pattern, ie this code opens these files, grabs their path, and closes the files again
您可以使用DIR
来查找与您的模式匹配的文件,即此代码打开这些文件,获取它们的路径,然后再次关闭这些文件
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