2013-02-13 51 views
1

我正在使用一個Excel電子表格,其中包含列A中的標題列表以及列D中的文件名列表。文件名是使用特定命名例如,如果A1中的標題是「Taco_123」,那麼D1中的文件名將包含精確的短語「Taco_123」。使用基於前一個單元格的路徑摘錄的文件名填充單元格

目前,文件名必須在創建文件後手動輸入到D1中。但是我想要的是一個可以自動完成的VBA腳本。我的想法是,對於每一行,它將讀取列A中的標題,在文件所在的目錄中搜索包含該確切短語的文件,然後將文件名稱(減去擴展名)複製到列D中。

這樣的事情甚至可能嗎?我試着在網上搜索一個解決方案,因爲我知道關於VBA的zilch,但我沒有太多的運氣;我甚至找不到有其他問題的人。任何幫助,將不勝感激。

編輯:我不知道這是否有所作爲,但需要搜索匹配文件名的文件類型是PSD。

+0

你有什麼試過的?什麼版本的Excel?一種方法是將所有帶有匹配擴展名的文件名拖拽到一個數組中,然後將每個文件名匹配到列D中的右邊一行。如何獲取文件夾中文件名的名稱取決於Excel的版本雖然。 – 2013-02-14 00:21:53

+0

@JamieBull It's excel 2010. – 2013-02-14 01:27:46

+0

您將不得不使用或修改P. Havdra的解決方案,此處: http://social.msdn.microsoft.com/Forums/zh-CN/isvvba/thread/a450830d- 4fc3-4f4e-aee2-03f7994369d6/ – 2013-02-14 02:27:19

回答

1

這樣的事絕對有可能。有一種簡單的方法可以在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 
+0

謝謝。那麼,我如何處理數組中的數據呢? Excel是否會自動知道將文件名輸出到相應的行/列? – 2013-02-14 04:03:00

+0

所有這些代碼都是在'sDir'變量指定的目錄中爲您生成一個PSD文件名的一維數組。你對數組做什麼(基本上是包含文件路徑的文件名列表**)取決於你。您需要確定匹配項,並可能需要使用一些字符串函數('InStr'和'Replace'),爲此,可以打印出所需的結果(文件路徑/目錄位置)到D列的工作表 – 2013-02-14 04:18:43

相關問題