如果條件不滿足,如何在上述事件期間關閉工作簿?

[英]How do you close a workbook during BeforeSave event if condition not met?


I am trying to close a workbook during the BeforeSave event if a condition is not met. I am using the following code and the save is canceled as expected but the close event crashes excel.

如果不滿足條件,我將試圖在上述事件期間關閉工作簿。我正在使用以下代碼,並按預期取消了保存,但是關閉事件會導致excel崩潰。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If X <> Y then
        Cancel = True
        ThisWorkbook.Close savechanges:=False
    End If
End Sub

I have even tried to call another Sub with the close command in it but that also produces the same issue

我甚至嘗試調用另一個包含close命令的子命令,但這也產生了相同的問題

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If X <> Y then
        Cancel = True
        ExitNoSave
    End If
End Sub

Public ExitNoSave ()
    ThisWorkbook.Close savechanges:=False
End Sub

Here is a screen grab from the code I made a new workbook with only the before save event and it still happens.

下面是我制作的一個新工作簿的代碼的屏幕抓取,它只包含了before save事件,並且仍然會發生。

enter image description here

enter image description here

Does anyone have a way to do this or is it not possible to do this from the BeforeSave event?

有沒有人有辦法做到這一點或者是不可能做到這一點?

1 个解决方案

#1


1  

Ok guys I figured it out you have to use the AfterSave event to accomplish this now apparently so if you cancel the save with the BeforeSave event it passes on that save failed to the AfterSave event you can then write your code for different conditions.

好了,伙計們,我算出來了你現在必須使用AfterSave事件來完成這個任務所以如果你用前面的事件取消save它會傳遞給那個save失敗的AfterSave事件然后你可以為不同的條件編寫代碼。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If 1 <> 2 Then
        Cancel = True
    End If
End Sub

Private Sub Workbook_AfterSave(ByVal Success As Boolean)
    If Success = False Then
        ThisWorkbook.Close savechanges:=False
    End If
End Sub

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/12/03/72faae7d5d61f856a3487a90553d879b.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com