这样的事情绝对是可能的。在 Excel 2003 及更早版本中使用 Application.FileSearch 在旧版本的 excel 中执行此操作有一个简单的方法。对于 2007 年及更新版本,您必须使用或修改 P. Havdra 的解决方案,此处:
http://social.msdn.microsoft.com/Forums/en-US/isvvba/thread/a450830d-4fc3-4f4e-aee2-03f7994369d6/
该脚本会打印出与您的搜索参数匹配的文件列表,并且还会弹出一个烦人的消息框。
我对他的 FileSearch 子程序进行了一些修改以帮助您入门。这会在指定目录中构建一组匹配的 PSD 文件名,然后您可以对数组进行处理并与工作表数据进行交互。
Sub FileSearch()
'
' Example of FileSearchByHavrda procedure calling as replacement of missing FileSearch function in the newest MS Office VBA
' 01.06.2009, Author: P. Havrda, Czech Republic
'As modified Feb-13-2013, David Zemens, for _
http://stackoverflow.com/questions/14865258/populate-cell-with-a-filename-based-on-path-excerpt-in-previous-cell
'
Dim sDir As String '< this is the search directory you will use
Dim FileNameWithPath As Variant
Dim ListOfFilenamesWithParh As New Collection ' create a collection of filenames
Dim rCount As Long 'row counter
Dim myArray() As Variant
Dim a As Long 'array iterator
a = 0
'Set the search directory:
sDir = "C:\DESKTOP\" '<-- MODIFY TO SUIT YOUR NEEDS
' Filling a collection of filenames (search Excel files including subdirectories)
Call FileSearchByHavrda(ListOfFilenamesWithParh, sDir, "*.psd", False)
' Print list to immediate debug window and as a message window
For Each FileNameWithPath In ListOfFilenamesWithParh ' cycle for list(collection) processing
'Create an array of matching filenames
ReDim Preserve myArray(a)
myArray(a) = FileNameWithPath
a = a + 1
Next FileNameWithPath
' If no file was found:
If ListOfFilenamesWithParh.Count = 0 Then
'Debug.Print "No file was found !"
MsgBox "No file was found !"
Else:
'some files were found, so do something with myArray
'########################################################
'
' <-- Code to manipulate your worksheet will go here -->
'
'
'########################################################
End If
End Sub