我在Excel 2010工作簿中有以下代码:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim FileName As String
FileName = ActiveWorkbook.Name
If FileName = "False" Then Exit Sub
If FileName <> "Shipping Manifest SaveAS Update.xlsm" Then
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=FileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled, WriteResPassword:="abc123", ReadOnlyRecommended:=True
Application.DisplayAlerts = True
End If
End Sub
如果我插入一个断点并逐行运行代码,代码就会执行,但是当我重新打开工作簿时,它不会提示&#34; abc123&#34;密码不以只读模式打开 - 它只是打开。我究竟做错了什么?我确保启用了宏。
答案 0 :(得分:1)
您已使用Application.DisplayAlerts = False
抑制了提醒。删除此行,您将看到问题所在。
禁用警报时,Excel将使用默认选项。在这种情况下,系统会警告您文件已存在,并且Excel要求您确认是否可以覆盖。此Yes / No / Cancel的默认选项为“No”,因此看起来文件实际上并未保存。
另一个潜在的问题是,您可能会混淆ThisWorkbook
和ActiveWorkbook
。 _BeforeClose
事件只会从它所在的工作簿运行,因此可以说没有理由进行任何类型的名称检查,假设您总是希望在关闭它时保存此代码所在的工作簿。
相反,请尝试:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
With ThisWorkbook
.WritePassword = "abc123"
.ReadOnlyRecommended = True
.Save
End With
End Sub
如果以编程方式关闭工作簿,则上述假设可能不成立,在这种情况下,可能需要区分ThisWorkbook
和ActiveWorkbook
,但很难想象为什么在关闭此工作簿时,您需要保存其他(活动)工作簿。
另外,对于Gary的上述评论(我已经测试了这个),如果你没有提供完整路径,那么该文件将保存到你的Documents文件夹中(至少在Excel 2013中对我来说)。
您可能需要这样做:
ActiveWorkbook.SaveAs FileName:=ActiveWorkbook.FullName, FileFormat:=xlOpenXMLWorkbookMacroEnabled, WriteResPassword:="abc123", ReadOnlyRecommended:=True
在您的代码中,为:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If ActiveWorkbook.Name <> "Shipping Manifest SaveAS Update.xlsm" Then
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=ActiveWorkbook.FullName, FileFormat:=xlOpenXMLWorkbookMacroEnabled, WriteResPassword:="abc123", ReadOnlyRecommended:=True
Application.DisplayAlerts = True
End If
End Sub
答案 1 :(得分:-1)
我删除了“取消为布尔”并且它完美地运行了
Private Sub Workbook_BeforeClose()
Dim FileName As String
FileName = ActiveWorkbook.Name
If FileName = "False" Then Exit Sub
If FileName <> "Shipping Manifest SaveAS Update.xlsm" Then
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=FileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled, WriteResPassword:="abc123", ReadOnlyRecommended:=True
Application.DisplayAlerts = True
End If
End Sub