为什么在运行宏时,ThisWorkbook.SaveCopyAs不起作用,但是当它没有运行时呢?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么在运行宏时,ThisWorkbook.SaveCopyAs不起作用,但是当它没有运行时呢?相关的知识,希望对你有一定的参考价值。
以下VBA代码旨在在MS Office 2003上运行。因为这就是我们数十亿美元的公司为我们提供的服务。 =)
好消息。如果我在IDE中编辑代码并点击保存,它的效果非常好。如果我正在处理电子表格本身,那就相同了。如果不存在,则创建备份文件夹,并在其中保存过时的备份副本。
坏消息。当我运行主宏(太大而不能发布)时,下面的代码执行但不保存备份副本。该事件被正确调用。实际上,如果不存在,它将创建备份文件夹。每一行都会运行。变量都是正确的。错误处理工作。
简单地说,如果主宏正在运行并且调用ThisWorkbook.Save,则ThisWorkbook.SaveCopyAs将不起作用。
我几个月前才为这个特定的项目学过VBA,所以如果有明显的东西就道歉。但是,我阅读了所有相关的MSDN文档和谷歌搜索疯狂,但没有出现。
提前感谢你的帮助。
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
答案
这是现有子的最后一部分,经过修改以创建副本。请注意,你不能使用内置的FileCopy
来制作副本(你会得到“Permission Denied”)
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
以上是关于为什么在运行宏时,ThisWorkbook.SaveCopyAs不起作用,但是当它没有运行时呢?的主要内容,如果未能解决你的问题,请参考以下文章
为啥 MSVC 在编译宏时大发雷霆,而 G++ 完全是关于禅的?