今天想讲解如何用VBA宏得到一个目录下以某个后缀名结尾的文件。
这要用到一个叫Dir的函数:
第一个参数就是所要遍历的目录路径,第二个参数是可选的,就是不是必要的。它是罗列了一些查找的属性
Syntax
Dir[(pathname [, attributes] )]
还是举个例子说说吧,现在我想得到C:\test\demo目录下的所有Excel 文件该如何作呢?
Sub SearchFolder(mypath As String, szExtension As String)
' Add a slash at the end of the path if needed.
If Right(mypath, 1) <> "\" Then
mypath = mypath & "\"
End If
' If there are no Excel files in the folder, exit.
FilesInPath = Dir(mypath & szExtension)
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
' Fill the myFiles array with the list of Excel files
' in the search folder.
FNum = 0
Do While FilesInPath <> ""
FNum = FNum + 1
ReDim Preserve MyFiles(1 To FNum)
MyFiles(FNum) = FilesInPath
FilesInPath = Dir()
Loop
End Sub