2016-02-26 147 views
0

我有一個在Excel中有50個文件路徑的列表。如何在網絡中搜索所有這些文件並將它們本地複製到我的文件夾? 如果路徑不存在於網絡中,我可以跳過這些嗎? 謝謝。VBA,使用文件路徑在本地複製和粘貼

EDIT ~~~

Sub Copy_Certain_Files_In_Folder() 
'This example copy all Excel files from FromPath to ToPath. 
'Note: If the files in ToPath already exist it will overwrite 
'existing files in this folder 
    Dim FSO As Object 
    Dim FromPath As String 
    Dim ToPath As String 
    Dim FileExt As String 

    FromPath = "I use network file here" '<< Change 
    ToPath = "local here" '<< Change 

    FileExt = "*.csv*" '<< Change 
    'You can use *.* for all files or *.doc for Word files 

    If Right(FromPath, 1) <> "\" Then 
     FromPath = FromPath & "\" 
    End If 

    Set FSO = CreateObject("scripting.filesystemobject") 

    If FSO.FolderExists(FromPath) = False Then 
     MsgBox FromPath & " doesn't exist" 
     Exit Sub 
    End If 

    If FSO.FolderExists(ToPath) = False Then 
     MsgBox ToPath & " doesn't exist" 
     Exit Sub 
    End If 

    FSO.CopyFile Source:=FromPath & FileExt, Destination:=ToPath 
    MsgBox "You can find the files from " & FromPath & " in " & ToPath 

End Sub 
+0

這對SO有多個答案。我首選的方法是使用scripting.filesystemobject的fileexist和其他函數查看這些關鍵字是否幫助您找到要查找的內容。 –

+0

@科迪G。感謝代碼-y! – Jonathan

+0

只供參考http://www.rondebruin.nl/win/s3/win026.htm –

回答

0

假設你的文件路徑是A列中的行上的片材名爲mysheetname這應該工作1至50。因爲這是在手機上輸入的,請原諒我的錯誤。

Sub MyCopyFiles() 
    Dim FSO 
    Set FSO = CreateObject("Scripting.FileSystemObject") 
    Dim newpath as string: newpath ="C:\temp\" 
    For i=1 to 50 
    If FSO.fileexists(Sheets("mysheetname").Cells(i,1)) then 
     Call FSO.CopyFile(Sheets("mysheetname ").Cells(i,1),newpath+FSO.getFilename(Sheets("mysheetname").Cells(i,1))) 
    End if 
    Next i 

End sub 
+0

科迪,我在哪裏把輸出文件夾也移動文件?或者你只是解釋這些代碼的輸入? – Jonathan

+0

用你想要的路徑替換C:\ temp \。注意它需要以\ –

+0

爲結尾我得到所需的對象'設置FSO = CreateObject(Scripting.FileSystemObject)'也將我的文件表更改爲「mysheetname」 – Jonathan