为什么在宏运行时不会使ThisWorkbook.SaveCopy工作,但是当它没有运行时它会工作?

时间:2015-02-08 19:40:43

标签: excel vba excel-vba io

以下 VBA 代码适用于 MS Office 2003 。因为这就是我们数十亿美元的公司为我们提供的服务。 =)

好消息。如果我在IDE中编辑代码并点击保存,它的效果非常好。如果我正在处理电子表格本身,那就相同了。如果不存在,则创建备份文件夹,并在其中保存过时的备份副本。

坏消息。当我运行主宏(太大而无法发布)时,下面的代码会执行,但不会保存备份副本。该事件被正确调用。实际上,如果不存在,它将创建备份文件夹。每一行都会运行。变量都是正确的。错误处理有效。

简单地说,如果主宏正在运行并且调用ThisWorkbook.Save,则ThisWorkbook.SaveCopyAs将不起作用。

我几个月前才为这个特定项目学过VBA,所以如果有明显的事情就道歉。但是,我阅读了所有相关的MSDN文档,并用Google搜索过疯狂,但没有出现。

提前感谢您的协助。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

'********************************************************************
'Purpose:   Triggered by ThisWorkbook.BeforeSave event
'           Creates backup folder and saves date appended copies
'********************************************************************

    Dim strBackupPath As String         'Path to Backup Folder
    Dim strFarkPath As String           'Path to running workbook
    Dim strBackupName As String         'Filename of backup
    Dim strFullName As String           'Full path & filename of running workbook
    Dim strBackupExtension As String    'Extension of backup
    Dim strDestination As String        'Full path & filename of backup
    Dim strDrive As String              'Drive letter

    strFarkPath = Application.ActiveWorkbook.Path
    strDrive = Left(strFarkPath, 1)
    strBackupPath = strFarkPath & "\_Backups"
    strBackupName = "\Backup-" & Year(Now) & "-" & Month(Now) & "-" & Day(Now)
    strFullName = Application.ActiveWorkbook.FullName
    strBackupExtension = Right(strFullName, Len(strFullName) - InStrRev(strFullName, ".", -1, vbTextCompare) + 1)
    strDestination = strBackupPath & strBackupName & strBackupExtension

    On Error GoTo Incorrect

    If Len(Dir(strBackupPath, vbDirectory)) = 0 Then
        MkDir strBackupPath
    End If

    Application.DisplayAlerts = False
    ThisWorkbook.SaveCopyAs Filename:=strDestination
    Application.DisplayAlerts = True
    Exit Sub

Incorrect:
    MsgBox "Unable to back record keeper up.  Next time, please run the program from a location where you can read and write files.", vbCritical + vbOKOnly

End Sub

1 个答案:

答案 0 :(得分:3)

这是现有子的最后一部分,经过修改后可以创建副本。 请注意,您无法使用内置FileCopy制作副本(您将获得"权限被拒绝")

    On Error GoTo Incorrect

    If Len(Dir(strBackupPath, vbDirectory)) = 0 Then
        MkDir strBackupPath
    End If

    Application.DisplayAlerts = False

    Application.EnableEvents = False
    ThisWorkbook.Save

    CreateObject("scripting.filesystemobject").copyfile _
                     ThisWorkbook.FullName, strDestination

    Application.EnableEvents = True '<<<<

    Application.DisplayAlerts = True

    Exit Sub

Incorrect:
    Application.EnableEvents = True 'never leave this False!
    MsgBox "Unable to back record keeper up.  Next time, please run the program from a location where you can read and write files.", vbCritical + vbOKOnly
End Sub