如果条件不满足,如何在上述事件期间关闭工作簿?

时间:2021-08-29 23:53:25

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事件,并且仍然会发生。

如果条件不满足,如何在上述事件期间关闭工作簿?

如果条件不满足,如何在上述事件期间关闭工作簿?

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

#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