2014-01-22 97 views
0

我有工作表(「sheet2」)中的文件名列表。我必須檢查文件夾中的這些文件,如果文件存在,則應將其複製到新文件夾中。我不知道從哪裏開始。任何人都可以引導我嗎?如何通過查找位置將文件複製到另一個文件夾

Dim rngFile as Range, cel as Range 
Dim desPath as String, filename as String, sourcePath as String 

Set rngFile = Thisworkbook.Sheets("Sheet2").Range("A1","A500") ' file list in ColA 

desPath = "D:\withdate\" 'Destination folder is withdate 
sourcePath = "D:\All\All\(fetch each cell for file name?)" 'source folde 

For Each cel in rngFile 
    If Dir(sourcePath & cel) <> "" Then 
    FileCopy sourcePath & cel, desPath & cel 'copy to folder 
End If 
Next 

末次

但上面的代碼不復制文件!

回答

1

試試這個:

Dim rngFile as Range, cel as Range 
Dim desPath as String, filename as String 

Set rngFile = Thisworkbook.Sheets("Sheet2").Range("A1","A500") 'assuming file list in ColA, change to suit 

desPath = "C:\User\Username\Desktop\YourFolder\" 'change to a valid path 

For Each cel in rngFile 
    If Dir(cel) <> "" Then 
     filename = Dir(cel) 'Returns the filename 
     FileCopy cel, desPath & filename 'copy to folder 
    End If 
Next 

End Sub 

這將具有相同文件名的文件移動到名爲YourFolder的文件夾Desktop中的新位置。
希望這會有所幫助。

EDIT1:

如果你只有帶擴展名的文件名

Dim rngFile as Range, cel as Range 
Dim desPath as String, filename as String, sourcePath as String 

Set rngFile = Thisworkbook.Sheets("Sheet2").Range("A1","A500") 'assuming file list in ColA, change to suit 

desPath = "C:\User\Username\Desktop\YourFolder\" 'change to a valid path 
sourcePath = "C:\Whatever\Here\" 

For Each cel in rngFile 
    If Dir(sourcePath & cel) <> "" Then 
     FileCopy sourcePath & cel, desPath & cel 'copy to folder 
    End If 
Next 

End Sub 

同樣,你在Sheet2的文件名應該有extension名稱(如Sample.xlsx,TEXT.TXT。) 。

+2

什麼是rngfile?如何獲取sheet2中的文件名並檢查它的存在? – Vidhi

+0

edited :)這就是你的清單所在。還添加了評論來指導您使用代碼。首先測試幾個樣品。 – L42

+0

爲了回答第二個問題,'Dir'檢查文件是否存在。如果文件存在,它將返回文件名。 – L42

0
+0

我有超過500張sheet2文件名我需要採取每個單元格值比較,如果文件存在?您建議的上述頁面不幫助我.. – Vidhi

+0

檢查頂部的新文檔,詳細說明循環遍歷單元格。在循環的每次迭代中,您都需要檢查文件是否存在,如果存在,則將其複製到目錄中。 – Andrew

相關問題