XL2003: Changing ThisWorkbook.Windows().Visible property during Workbook_BeforeClose event prevents workbook from closing

情到浓时终转凉″ 提交于 2019-12-24 01:18:30

问题


As title. This is driving me mad and I can't find any reference to it anywhere else on the web.

I have a VBA-laden workbook which is normally hidden through use of:

ThisWorkbook.Windows(1).Visible = False

However, when the workbook is closed I need it to revert to a default state whereby its window is visible and a "special" worksheet which instructs the user on enabling macros is shown. This is to provide guidance should the next user open the workbook with macros disabled. When the workbook is opened with macros enabled, the Workbook_Open event takes care of hiding this message again, at which point normal operation proceeds.

My problem is that when I change the .Windows().Visible property from the workbook's _BeforeClose event (which only occurs whenever Excel is quitting) the workbook simply remains on screen. I have confirmed that it is definitely setting the .Windows().Visible property that is causing this behaviour.

I have tried using the ThisWorkbook.IsAddin property, since this has the same effect of "hiding" the workbook from the user's view, but that causes exactly the same behaviour.

I have also tried simply not changing the window's visibility in any way, in the hope that subsequently opening the workbook with macros disabled will cause the property to be ignored, but this is not the case.

The only thing that I can do to cause the desired behaviour is to have ThisWorkbook.Close as the last line of the _BeforeClose event itself, but this causes instability which manifests as an occasional "Excel has closed unexpectedly, do you want to recover/restart?" message after Excel has quit.

Any help/pointers gratefully accepted. I don't have access to a later version of Excel.

My code:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    Application.ScreenUpdating = False

    Call cleanUp

    Application.ScreenUpdating = True

End Sub

and

Private Sub cleanUp()

Dim s As Worksheet

    shtZNM.Visible = xlSheetVisible

    For Each s In ThisWorkbook.Sheets
        If Not s Is shtZNM Then s.Visible = xlSheetHidden
    Next s

    With ThisWorkbook.Windows(1)
        .DisplayWorkbookTabs = False
        .DisplayHorizontalScrollBar = False
        .DisplayVerticalScrollBar = False
        .Visible = True '<==REMOVING THIS ALLOWS _BEFORECLOSE TO WORK AS EXPECTED
    End With

    On Error Resume Next
    Application.CommandBars("QCS").Delete
    Err.Clear
    Application.CommandBars("Worksheet Menu Bar").Controls("QCS").Delete

    Me.Save

End Sub

来源:https://stackoverflow.com/questions/14854023/xl2003-changing-thisworkbook-windows-visible-property-during-workbook-beforec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!