I am trying to create a backup database on a.network drive using fso.folder copy. My intention is to move all files within the folder, but if a file already exists on the backup drive, skip it, and copy the remainder of the files in the folder. I currently have
SourceFileName="C:\users\desktop\test1"
DestinFileName="C:\users\desktop\test2"
FSO.copyfolder Source:=Sourcefilename, Destination:=Destinfilename, OverwriteFiles:= False
However, the script errors when it finds the existing file. Any advice would be appreciated.
On Error
on the folder part
.The Code
Option Explicit
Sub copyFilesNoOverwrite()
Const srcFolderPath As String = "C:\users\desktop\test1"
Const dstFolderPath As String = "C:\users\desktop\test2"
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(srcFolderPath) Then
MsgBox "Source Folder doesn't exist.", vbCritical, "No Source"
Exit Sub
End If
If .FolderExists(dstFolderPath) Then
Dim Sep As String: Sep = Application.PathSeparator
Dim fsoFile As Object
Dim FilePath As String
For Each fsoFile In .GetFolder(srcFolderPath).Files
FilePath = dstFolderPath & Sep & fsoFile.Name
If Not .FileExists(FilePath) Then
.CopyFile _
Source:=fsoFile.Path, _
Destination:=FilePath
End If
Next fsoFile
Else
.CopyFolder _
Source:=srcFolderPath, _
Destination:=dstFolderPath
End If
End With
End Sub
Sub copyFilesNoOverwriteOnError()
Const srcFolderPath As String = "C:\users\desktop\test1"
Const dstFolderPath As String = "C:\users\desktop\test2"
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(srcFolderPath) Then
MsgBox "Source Folder doesn't exist.", vbCritical, "No Source"
Exit Sub
End If
If .FolderExists(dstFolderPath) Then
Dim Sep As String: Sep = Application.PathSeparator
Dim fsoFile As Object
For Each fsoFile In .GetFolder(srcFolderPath).Files
On Error Resume Next
.CopyFile _
Source:=fsoFile.Path, _
Destination:=dstFolderPath & Sep & fsoFile.Name, _
OverwriteFiles:=False
On Error GoTo 0
Next fsoFile
Else
.CopyFolder _
Source:=srcFolderPath, _
Destination:=dstFolderPath
End If
End With
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.