Search code examples
excelvbapromptinputbox

VBA InputBox Prompts Twice


I have a simple script to require a password before closing a workbook (to prevent accidental closing), but the InputBox re-opens if I enter the correct keyword. I have created multiple iterations of the below script, but I cannot resolve it.

Sub Workbook_BeforeClose(Cancel As Boolean)

If InputBox("Please enter the password to close the workbook.") <> "pa55word" Then
    MsgBox ("Incorrect password.  Please try again")
    Cancel = True
    Exit Sub
Else
    GoTo GoToClose
End If

GoToClose:
ThisWorkbook.Close SaveChanges:=False

End Sub

Solution

  • If you code it like this:

    • the code simply proceeds to save the workbook if the password is correctly without a second close
    • The ThisWorkbook.Saved at front tells Excel the workbook is fully updated so there wont be a do you want to save message - ie it does the same task as the False part of ThisWorkbook.Close SaveChanges:=False and the existing Save event closes the workbook.

    recut

    Sub Workbook_BeforeClose(Cancel As Boolean)
    
    ThisWorkbook.Saved = True
    If InputBox("Please enter the password to close the workbook.") <> "pa55word" Then
         MsgBox ("Incorrect password.  Please try again")
         Cancel = True
    End If
    
    End Sub