簡體   English   中英

Excel VBA 復制文件夾,移動所有文件 - 但如果文件存在則跳過

[英]Excel VBA copy folder, move all files - but if file exists skip

我正在嘗試使用 fso.folder 副本在網絡驅動器上創建備份數據庫。 我的意圖是移動文件夾中的所有文件,但如果備份驅動器上已存在文件,請跳過它,並復制文件夾中的其余文件。 我目前有

SourceFileName="C:\users\desktop\test1"
DestinFileName="C:\users\desktop\test2"

FSO.copyfolder Source:=Sourcefilename, Destination:=Destinfilename, OverwriteFiles:= False

但是,腳本在找到現有文件時出錯。 任何意見,將不勝感激。

復制文件而不覆蓋

  • 我會推薦第一個解決方案。 文檔“有點引導您”(至少我)使用第二種解決方案。 由您決定第二個是否更有效率。 您不能在folder part應用On Error

代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM