创建文档的备份

时间:2016-02-02 16:54:04

标签: vba ms-word

我的宏应该对当前正在保存的文件进行备份(在指定的路径中),这个过程经常被讨论,因为它是Word缺少的功能。

Private Sub Document_Close()
Dim blank As Range
    For Each blank In ActiveDocument.StoryRanges
    If Len(blank.Text) = 1 Then Exit Sub
    Next
End Sub

Sub FileSave()
Dim BackupPath As String, objF As Object, retVal As Long, Rslt
BackupPath = "C:\Users\" & Environ("UserName") & "\Documents\BackupWord\"
With ActiveDocument
  If .Path = "" Then: If Application.Dialogs(wdDialogFileSaveAs).Show <> -1 Then Exit Sub
  If Len(Trim(.Range.Text)) = 1 Then Exit Sub
   .Save
  If Dir(BackupPath, vbDirectory) = "" Then
    MkDir BackupPath
    MsgBox "Backup folder has been created.", vbInformation
  End If
  If .Path & "\" = BackupPath Then
    MsgBox "WARNING! Backup folder is the same as the source folder", vbExclamation
    Exit Sub
  End If
  Set objF = CreateObject("Scripting.FileSystemObject")
  retVal = -1
  On Error Resume Next
  retVal = objF.CopyFile(.FullName, BackupPath & .Name, True)
  On Error GoTo 0
  Set objF = Nothing
  If retVal <> 0 Then MsgBox "Backup has not been copied to folder " BackupPath, vbExclamation
End With
End Sub

我将描述宏当前的作用。

  1. 拦截了FileSave程序。
  2. 宏检查是否保存了活动文档。如果是,则不需要额外的操作,宏关闭。
  3. 如果未保存活动文档,则会显示通常的“另存为”对话框。如果用户选择不保存文件,则宏关闭。
  4. 如果未保存文档,则宏会保存它。
  5. 宏查找备份文件夹。如果找不到,宏将创建它并显示一个消息框。
  6. 然后宏检查源文件夹是否与备份文件夹相同。如果它们相同,宏将显示一条消息并关闭。
  7. 将活动(当前)文档复制到备份文件夹。如果失败,则会显示一个消息框。
  8. 我的宏无法两次备份。

    1. 当我打开Word(没有打开文档,只是空白页面)时,修改它 并选择关闭Word,显示SaveAs对话框。然后我选择 保存并正确保存文档但不保存备份副本 创建。
    2. 当文件存在时,例如,硬盘驱动器,pendrive等。 我将修改它并选择关闭Word,显示一个SaveAs对话框。 然后我选择保存并正确保存文档但是a 未创建备份副本。

1 个答案:

答案 0 :(得分:1)

你需要一个班级,我相信在addin级别跟踪所有表格,比如......

Option Explicit

    Private WithEvents wd As Word.Application

    Public Sub initialise(w As Word.Application)
        Set wd = w
    End Sub

    Private Sub wd_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
           '   Your code here
    End Sub

在您的插件(.dotm)文件中,您有以下内容

Option Explicit
Public c As clsCustomWord

Sub AutoExec()
    Set c = New clsCustomWord
    c.initialise Application
End Sub

希望这有帮助