vba savecopyas:如何打开复制的工作簿,然后删除它的VBA脚本

时间:2013-12-05 18:26:48

标签: vba excel-vba copy excel

我在关闭提示代码处有一个savecopyas代码,但是如果有人打开复制的文档然后尝试关闭它,那么同一个复制的VBA脚本会尝试将savecopyas运行到它自己的路径,导致错误/调试消息框。我的第一个想法是在后台打开复制的工作簿并删除所有VBA脚本然后关闭并保存为只读,但我也想到也许我应该尝试将复制的工作簿更改为.xlsx而不是它& #39;原始版本.xslm格式。 有什么建议吗?

这是我到目前为止所做的,但我的问题是我如何打开复制的工作簿(不是原始的)并在后台删除其中的VBA脚本(不可见)然后保存并关闭? 任何帮助/建议将不胜感激。

这是在我的'ThisWorkBook'模块:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Not Me.Saved Then
    Msg = "Do you want to save the changes you made to "
    Msg = Msg & Me.Name & "?"
    Ans = MsgBox(Msg, vbQuestion + vbYesNoCancel)
    Select Case Ans
        Case vbYes
            Me.Save
        Case vbNo
            Me.Saved = True
        Case vbCancel
            Cancel = True
            Exit Sub
      End Select
End If
Call Auto_Save 'Change this to your own subroutine
End Sub

这是我的' Module1':

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim backupfolder As String

backupfolder = "C:\Users\" & Environ("username") & "\Documents\John's Backup\"

ThisWorkbook.SaveCopyAs Filename:=backupfolder & ThisWorkbook.Name
End Sub

Sub Auto_Save()

Dim savedate

savedate = Date

Dim savetime
savetime = Time
Dim formattime As String
formattime = Format(savetime, "hh.MM.ss")
Dim formatdate As String
formatdate = Format(savedate, "DD - MM - YYYY")

Application.DisplayAlerts = False

Dim backupfolder As String
backupfolder = "C:\Users\" & Environ("username") & "\Documents\John's Backup\"
ActiveWorkbook.SaveCopyAs Filename:=backupfolder & ActiveWorkbook.Name
ActiveWorkbook.Save
Application.DisplayAlerts = True
MsgBox "Backup Run. Please Check at: " & backupfolder & " !"

End Sub

1 个答案:

答案 0 :(得分:2)

您钉它 - 通过将工作簿保存为xlsx文件来删除宏(假设您使用的是Excel 2007+)。

如果我正确了解您的情况,则在工作簿关闭时会保存工作簿备份。所以,我会保存工作簿,然后SaveAs工作簿,然后关闭工作簿。

一个实现看起来像this

ActiveWorkbook.Save
' Note that xlOpenXMLWorkbook = 41
ActiveWorkbook.SaveAs backupfolder & ActiveWorkbook.Name, FileFormat:= xlOpenXMLWorkbook 

另外,如果用户位于较旧版本的Windows上(或者如果将来的版本具有Documents文件夹的不同位置),则文件夹位置可能会失败。所以,而不是:

backupfolder = "C:\Users\" & Environ("username") & "\Documents\John's Backup\"

执行this

之类的操作
Dim WshShell as Object
Set WshShell = CreateObject("WScript.Shell")
backupfolder = WshShell.SpecialFolders("MyDocuments") + "\John's Backup\"