首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Excel VBA复制文件夹,移动所有文件-但如果文件存在,则跳过

Excel VBA复制文件夹,移动所有文件-但如果文件存在,则跳过
EN

Stack Overflow用户
提问于 2020-12-23 00:47:30
回答 1查看 317关注 0票数 1

我正在尝试使用fso.folder copy在网络驱动器上创建备份数据库。我的意图是移动文件夹中的所有文件,但如果备份驱动器上已存在某个文件,请跳过该文件,然后复制该文件夹中的其余文件。我目前有

代码语言:javascript
复制
SourceFileName="C:\users\desktop\test1"
DestinFileName="C:\users\desktop\test2"

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

但是,该脚本在找到现有文件时会出错。任何建议都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2020-12-23 02:05:10

复制文件而不覆盖

  • ,我推荐第一个解决方案。documentation正在“某种程度上引导你”(至少是我)使用第二种解决方案。这取决于你是否发现第二个可能更有效率。您不能在folder part.

上应用On Error

代码

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65412587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档