這樣的事絕對有可能。有一種簡單的方法可以在Excel,舊版Excel中使用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
你有什麼試過的?什麼版本的Excel?一種方法是將所有帶有匹配擴展名的文件名拖拽到一個數組中,然後將每個文件名匹配到列D中的右邊一行。如何獲取文件夾中文件名的名稱取決於Excel的版本雖然。 – 2013-02-14 00:21:53
@JamieBull It's excel 2010. – 2013-02-14 01:27:46
您將不得不使用或修改P. Havdra的解決方案,此處: http://social.msdn.microsoft.com/Forums/zh-CN/isvvba/thread/a450830d- 4fc3-4f4e-aee2-03f7994369d6/ – 2013-02-14 02:27:19