如何在VBA中复制或备份文件

时间:2019-06-26 17:46:40

标签: excel vba file copy backup

这是2个用于复制或备份文件的VBA子例程。

Sub File_Backup(Path, Orig_File_Name)
    ' Make a Backup copy of a file
    ' 6/25/19 Craeated. WML

    ' Note: "{Backup}" is used to put the new file under the original _
            File Name in File Explorer.

    Prog = "File_Backup"

    ' Get File extention.
    Test_Ptr = 0
    Do
        Ptr = Test_Ptr
        Test_Ptr = InStr(Test_Ptr + 1, Orig_File_Name, ".")
    Loop Until Test_Ptr = 0
    File_Name = Left(Orig_File_Name, Ptr - 1)
    Extention = Mid(Orig_File_Name, Ptr)

    New_File_Name = File_Name & "{Backup}" & Extention
    Call File_Copy(Path, Orig_File_Name, Path, New_File_Name)

End Sub ' File_Backup

Sub File_Copy(From_Path, From_Name, To_Path, To_Name, _
                Optional Overwrite as Boolean = True)
    ' Copy a file from one place to another.
    ' 6/26/19 WML

    Prog = "File_Copy"

    Dim oFSO As Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")

    If Right(To_Path, 1) <> "\" Then To_Path = To_Path & "\"
    If Right(From_Path, 1) <> "\" Then From_Path = From_Path & "\"

    Call oFSO.CopyFile(From_Path & From_Name, To_Path & To_Name, Overwrite)

End Sub ' File_Copy

除非您尝试将文件复制到相同的名称并且“ Overwrite” = False(不会被系统错误捕获),否则不会出错。

0 个答案:

没有答案