PDA

View Full Version : Exit Userform and close excel



Student1000
05-27-2010, 01:45 AM
Hello, I want to prevent the user from accessing the excel spreadsheets.
therefore I disable the close command (the cross in the upper right corner to close a window) and ask him to use a cancel button.

What should happen when user exits the userform:
The user will then be asked if he really wants to close or not. There he can choose between OKAY and Cancel. If he presses okay he will exit the Userform and Excel will close automatically. However, If he presses Cancel he should stay on the userform.

My problem:
When the user is asked if he "really wants to close" and presses the cancel button, excel stays open and the userform closes. BUT the userform should stay open and excel should be hidden....

Here is my code

In this workbook:


Private Sub Workbook_open()
Application.WindowState = xlMinimized 'user cannot see what is entered in Excel
AppActivate ("Microsoft Excel")
UserForm1.Show

End Sub


Private Sub Workbook_BeforeClose(Cancel As Boolean)
If (MsgBox(prompt:=" Do you really want to close?", Buttons:=vbOKCancel) = vbCancel) Then
Cancel = True
Else
Cancel = False
End If

If Cancel = False Then
Application.Quit
End If

End Sub


and in the UserForm I used this code for the cancel Button:


Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode <> 1 Then Cancel = 1
MsgBox ("Please click the Cancel button to exit the program")
End Sub

Private Sub CMD_Cancel_Click()
ActiveWorkbook.Close savechanges = True
Unload Me
End Sub

Bob Phillips
05-27-2010, 03:02 AM
How about doing it all in the form



Private Sub CMD_Cancel_Click()
If MsgBox(prompt:=" Do you really want to close?", Buttons:=vbOKCancel) = vbOK Then

ActiveWorkbook.Save
Application.Quit
End If
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then

Cancel = True
Call CMD_Cancel_Click
End If
End Sub