将文件从一个目标文件夹复制到另一个文件夹

时间:2021-04-09 16:04:12

I am currently trying to copy a file from one folder to another specified folder using Excel VBA Macro,my data is on Sheet 1 on Excel, I've set my file name to be on cell B5, the source folder is on B6, and the destination folder is on cell B7. This is my code below :

我正在尝试用Excel VBA宏将一个文件从一个文件夹复制到另一个指定的文件夹,我的数据在Excel表1上,我把我的文件名设置在cell B5上,源文件夹在B6上,目标文件夹在cell 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

but a "Specified File Not Found in Source Folder" error message keeps on popping up even though the file is in the source folder. Please assist

但是“未在源文件夹中找到的指定文件”错误消息继续弹出,即使该文件在源文件夹中。请协助

2 个解决方案

#1


1  

when using sSFolder & sFile make sure you have a "\" between the 2 variables, like this

使用sSFolder & sFile时,请确保两个变量之间有一个“\”,如下所示

sSFolder & "\" & sFile

#2


0  

Use path separator:

使用路径分隔符:

If Not FSO.FileExists(sSFolder & Application.PathSeparator & sFile) Then

#1


1  

when using sSFolder & sFile make sure you have a "\" between the 2 variables, like this

使用sSFolder & sFile时,请确保两个变量之间有一个“\”,如下所示

sSFolder & "\" & sFile

#2


0  

Use path separator:

使用路径分隔符:

If Not FSO.FileExists(sSFolder & Application.PathSeparator & sFile) Then