2017-06-14 135 views
1

我目前正在嘗試使用Excel VBA宏將一個文件從一個文件夾複製到另一個指定文件夾,我的數據位於Excel的Sheet 1上,我已將文件名設置爲打開單元格B5,源文件夾位於B6上,目標文件夾位於單元格B7上。這是我下面的代碼:將文件從一個目標文件夾複製到另一個目標文件夾

'In this Example I am Copying the File From one loaction to another location 
'as per the details specified in the Worksheet. 
Sub sbCopyingAFileReadFromSheet() 
'Declaration 
Dim FSO 
Dim sFile As String 
Dim sSFolder As String 
Dim sDFolder As String 

sFile = Sheets("Sheet1").Range("B5") 

sSFolder = Sheets("Sheet1").Range("B6") 

sDFolder = Sheets("Sheet1").Range("B7") 

Set FSO = CreateObject("Scripting.FileSystemObject") 

If Not FSO.FileExists(sSFolder & sFile) Then 
MsgBox "Specified File Not Found in Source Folder", vbInformation, "Not Found" 

ElseIf Not FSO.FileExists(sDFolder & sFile) Then 
FSO.CopyFile (sSFolder & sFile), sDFolder, True 
MsgBox "Specified File Copied to Destination Folder Successfully", vbInformation, "Done!" 
Else 
MsgBox "Specified File Already Exists In The Destination Folder", vbExclamation, "File Already Exists" 
End If 
End Sub 

而是一個「指定文件中的源文件夾Not Found」錯誤消息不斷彈出即使該文件是在源文件夾中。使用sSFolder & sFile確保你有2個變量之間的「\」,這樣

sSFolder & "\" & sFile 
+0

是一個本地驅動器類似的文件* * C:\ **或在像** \\某處的網絡驅動器上** –

+1

單元格B5,B6,B7中的值是多少?你是否在文件夾路徑和文件路徑之間加入'「\」?是其擴展名的文件名? – Maddy

+0

我意識到我沒有在文件夾路徑的末尾添加「\」。 – Kwezi

回答

1

If Not FSO.FileExists(sSFolder & Application.PathSeparator & sFile) Then 
相關問題