简体   繁体   中英

VBA: Workbook.Close loop

I have the following portion of the code for a given active worksheet:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

Dim sh As Worksheet
Dim myMessage
    If ActiveSheet.Range("I5").Value > 0 Then
        MsgBox "Some cells are empty" _
        & Chr(13) & Chr(13) & "Please, fill in the empty cells to proceed", _
        vbExclamation + vbOKOnly, "ERROR!"
        Cancel = True
    Else
        ThisWorkbook.Unprotect ("123")
        Worksheets("Instructions").Visible = True
        Worksheets("Instructions").Activate
        For Each sh In Worksheets
            If sh.Name <> "Instructions" Then
                sh.Visible = xlVeryHidden
            End If
        Next sh
        ThisWorkbook.Protect ("123")
        myMessage = MsgBox("Do you want to save and close this file?", vbQuestion + vbYesNo, "Workbook 1")
            If myMessage = vbYes Then
                Application.DisplayFormulaBar = True                    
                ThisWorkbook.Close True
            ElseIf myMessage = vbNo Then
                Cancel = True
            Else
                'nothing
            End If

    End If
End Sub

In general, upon pressing the close button on the workbook itself, the idea is to check a given cell of a given active worksheet for a non-zero value. If it is non-zero, the user has to fill in certain empty cells first and the workbook is not closed. Alternatively, the "Instruction" worksheet is activated and the user receives a message box of what to do next (by doing this, instead of simply no msgbox and sticking with the usual system "SAVE/NO" prompt, is that I want to eliminate the possibility of a user pressing the "No" button, which will lead to no save being made). The only problem I have is the one-time loop I get when a user selects "Yes" answer: the same message box re-appears (apparently, because the procedure goes through the code line again!). I would appreciate if you could suggest me the way I could avoid this loop.

If you are not going to allow the user not to save then why not force a save. You can replace the entire message box prompt section:

myMessage = MsgBox("Do you want to save and close this file?", vbQuestion + vbYesNo, "Workbook 1")
        If myMessage = vbYes Then
            Application.DisplayFormulaBar = True                    
            ThisWorkbook.Close True
        ElseIf myMessage = vbNo Then
            Cancel = True
        Else
            'nothing
        End If

with

ThisWorkbook.Save

This will force the save and close the workbook.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM