warning message doesn't work for user-form - vba

My content in sheet2 was hidden and only after user form popped up and enter the password before the content can unhide. However with the warning message, even after I select "yes to terminate" my sheet content still unhides.
Expected outcome:
After the user selects "yes to terminate" on the warning message, it is suppose to drop the user form. Can anyone help me solve it?
Under worksheet(sheet2):
Private Sub Worksheet_Activate()
If Sheets("Reference").Columns("A:K").EntireColumn.Hidden = True Then
Password.Show
Call unhide
Else
Sheets("Reference").Columns("A:K").EntireColumn.Hidden = False
End If
End Sub
Under userform (Password):
Private Sub Submit_Click()
If Me.Pword.Value = "123" Then
Unload Me
Call unhide
Else
Me.Hide
Retry = MsgBox("The password is incorrect. Do you wish to try again?", _
vbYesNo, "Retry?")
Select Case Retry
Case Is = vbYes
Me.Pword.Value = ""
Me.Pword.SetFocus
Me.Show
Case Is = vbNo
Unload Me
End Select
End If
End Sub
Private Sub cmdExit_Click()
If ExitAsk = vbYes Then Unload Password
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
If Not ExitAsk = vbYes Then Cancel = True
End If
End Sub
Private Function ExitAsk() As VbMsgBoxResult
Dim Smsg As String
Smsg = "Do you really want to exit? Click Yes to Quit or No to Continue."
ExitAsk = MsgBox(Smsg, vbYesNo + vbDefaultButton2 + vbQuestion, "Exit!")
End Function

Related

Pop up message before closing a file

I need a pop-up message to remind the person to check all the information before closing the presentation, with two choices (to cancel or to close it anyway).
Private Sub PPTApp_PresentationBeforeClose(Cancel As Boolean)
If MsgBox("Confirmo que as informações desta apresentação estão atualizadas no SAP", _
vbQuestion + vbYesNo) = vbNo Then
Cancel = True
End If
End Sub
Try This.
Private Sub PPTApp_PresentationBeforeClose(Cancel As Boolean)
Dim i As Long
i = MsgBox("your message will appear here", vbQuestion + vbYesNo)
If i = vbNo Then
'do this command
Else
' do this command
End If
End Sub

How to prevent sharepoint file checkin from triggering workbook before close?

My sub Workbook_BeforeClose runs twice, because in my Sub CloseWBFromSharePointFolder, I either check in my file, discard it or cancel and do nothing (see code below). Both the check in and the discarding of the file trigger Workbook_BeforeClose to run again.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
CloseWBFromSharePointFolder
End Sub
Both snippets from CloseWBFromSharePointFolder which trigger Workbook_BeforeClose
Check in
ActiveWorkbook.CheckIn SaveChanges:=True, Comments:="Checked-In by " & Application.Username
Discard
Application.ActiveWorkbook.CheckIn False
Any help would be appreciated.
P.s. I also tried to use a public variable to track if it runs again. This does not work because the public variable got reset. The explanation I found is because Workbook_BeforeClose calls CloseWBFromSharePointFolder, which then triggers Workbook_BeforeClose. This resets everything and the public variable becomes empty
P.s.2 for more details.
CloseWBFromSharePointFolder Code
Sub CloseWBFromSharePointFolder()
Dim myForm1 As UserForm1
Set myForm1 = UserForm1
myForm1.Caption = "Choose before closing:"
myForm1.Show
End Sub
UserForm1 Code
Dim Buttons() As New BtnClass
Private Sub UserForm_Initialize()
Dim ButtonCount As Integer
Dim ctl As Control
' Create the Button objects
ButtonCount = 0
For Each ctl In UserForm1.Controls
If TypeName(ctl) = "CommandButton" Then
'Skip the OKButton
If ctl.Name <> "OKButton" Then
ButtonCount = ButtonCount + 1
ReDim Preserve Buttons(1 To ButtonCount)
Set Buttons(ButtonCount).ButtonGroup = ctl
End If
End If
Next ctl
Me.CommandButton1.Caption = "Check in"
Me.CommandButton2.Caption = "Discard check-out"
Me.CommandButton3.Caption = "Keep checked-out"
Me.CommandButton4.Caption = "Cancel"
End Sub
BtnClass Code
Public WithEvents ButtonGroup As MsForms.CommandButton
Private Sub ButtonGroup_Click()
If UserForm1.Visible = True Then
Select Case ButtonGroup.Name
Case "CommandButton1" 'check in
CheckIn
Case "CommandButton2" 'Discard check-out
Discard
Case "CommandButton3" 'Keep checked-out
KeepCheckedOut
Case Else ' Cancel
'Do Nothing
End Select
Unload UserForm1
ElseIf UserForm2.Visible = True Then
Select Case ButtonGroup.Name
Case "CommandButton1" 'check out
CheckOut
Case "CommandButton2" 'Read only
'Do Nothing
Case Else ' Cancel
'Do Nothing
End Select
Unload UserForm2
End If
End Sub
Sub CheckIn()
If ActiveWorkbook.CanCheckIn = True Then
'Check In, Save and Close
ActiveWorkbook.CheckIn SaveChanges:=True, Comments:="Checked-In by " & Application.Username
MsgBox ("File sucessfully checked in")
Else
MsgBox ("File could not be checked in!")
End If
End Sub

BeforeUpdate with a "new record" button

I have an Access form users sometimes forget to save. I put in a BeforeUpdate trigger to pop up message reminding users to save or cancel before taking any action.
I found this code on the net and it works for everything except my "New Record" button.
As far as I know Me.Dirty should do the trick.
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim ctl As Control
On Error GoTo Err_BeforeUpdate
' The Dirty property is True if the record has been changed.
If Me.Dirty Then
' Prompt to confirm the save operation.
If MsgBox("Do you want to save?", vbYesNo + vbQuestion, _
"Save Record") = vbNo Then
Me.Undo
End If
End If
Exit_BeforeUpdate:
Exit Sub
Err_BeforeUpdate:
MsgBox Err.Number & " " & Err.Description
Resume Exit_BeforeUpdate
End Sub
The code for the new record
Private Sub new_Click()
njno = NewJobNbr()
Job.Value = njno
RnK.Value = ""
Date_Requested.Value = ""
Est_Time.Value = ""
Originator.Value = ""
Date_Required.Value = ""
Description.Value = ""
Reason_for_Request.Value = ""
Comments.Value = ""
Priority_Tasks.Value = ""
TName.Value = ""
Required.Value = ""
Costing.Value = ""
Completed.Value = ""
Date_Completed.Value = ""
End Sub
I don't really understand what njno is. If the textboxes are bound to the form's RecordSource then.
On form Current event use:
Private Sub Form_Current ()
If Me.NewRecord Then
Job.Value = njno
End if
End Sub
Then on the button Click event use:
Private Sub new_Click()
DoCmd.GoToRecod,,acNewRec
End sub

How to exit a VBA macro when the form's "X" button is clicked?

I have an Outlook macro that pops up a form when someone sends an email and asks them to select a classification. Under ThisOutlookSession I have:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim frm As classificationForm
Dim chosenvalue As String
Set frm = New classificationForm
frm.Show vbModal
Select Case True
Case frm.restrictedButton.Value
chosenvalue = "Restricted"
Case frm.internalButton.Value
chosenvalue = "Internal"
Case frm.publicButton.Value
chosenvalue = "Public"
Case Else
MsgBox "No classification chosen"
Cancel = True
Exit Sub
End Select
If TypeName(Item) = "MailItem" Then
Item.Subject = "[" & chosenvalue & "] " & Item.Subject
End If
End Sub
and under classificationForm I have:
Private Sub okCommand_Click()
Unload Me
End Sub
Private Sub cancelCommand_Click()
Unload Me
End Sub
The form is 3 option buttons (the classifications) and 2 command buttons (OK and Cancel).
The [Internal] option button is selected by default. However, if someone clicks the form's "X" button in the top-right corner or the "Cancel" command button, then the Macro sends the email with the selected classification button when I want it to kick me back to the draft email like it would if there were no options selected.
How would I do this? Thanks.
Unload is a lie. It seems to only work with the form's default instance, and working with forms' default instance is a poisonous place you don't want to go.
Don't unload. Hide instead.
Another problem is that since the calling code is querying the form's controls' state, it doesn't matter how the form was closed: Ok, Cancel, "X" - everything single one of these buttons gets the form unloaded and whatever was selected is acted upon: you have no mechanism in place to determine whether the user okayed the dialog, or wishes to cancel everything.
Add a Cancelled property:
Private IsCancelled As Boolean
Public Property Get Cancelled() As Boolean
Cancelled = IsCancelled
End Property
Handle the QueryClose event, set the Cancel parameter to False when the CloseMode is vbFormControlMenu, and Hide the form - actually, what you want is for that "X" button to do exactly the same thing as your Cancel button, so just do that:
Private Sub OkButton_Click()
Me.Hide
End Sub
Private Sub CancelButton_Click()
OnCancel
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
Cancel = True
OnCancel
End If
End Sub
Private Sub OnCancel()
IsCancelled = True
Me.Hide
End Sub
Now your calling code can determine whether the form was cancelled, and act accordingly.
If frm.Cancelled Then
Cancel = True
Else
'user okayed the dialog: determine the selection...
End If
See this article for more in-depth information about user forms: the calling code doesn't need to care about the controls on the form.
use UserForm_QueryClose() event handler to intercept any userform red "X" clicking
then change your UserForm code pane as follows:
Private Sub okCommand_Click()
Me.Hide ' don't unload the Form, just hide it
End Sub
Private Sub cancelCommand_Click()
Me.Tag = "NO" ' signal to the calling sub that it must not send the email
Me.Hide ' don't unload the Form, just hide it
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then Me.Tag = "NO" ' if user clicked the red X button signal to the calling sub that it must not send the email
End Sub
and adjust your Application_ItemSend event handler code accordingly:
Set frm = New classificationForm
With frm
.Show vbModal
If .Tag <> "NO" Then ' if userform didn't signal not to send the email
Select Case True
Case frm.restrictedButton.Value
chosenvalue = "Restricted"
Case frm.internalButton.Value
chosenvalue = "Internal"
Case frm.publicButton.Value
chosenvalue = "Public"
Case Else
MsgBox "No classification chosen"
Cancel = True
Exit Sub
End Select
Else ' the userform signaled not to send the email
MsgBox "No classification chosen"
Cancel = True
End If
End With
Unload frm

Access/VBA: "Run-time error 2169. You can't save this record at this time"

Using: Access 2013 with ADO connection to SQL Server back-end database
A form in my Access database is dynamically bound at runtime to the results of a SELECT stored-procedure from SQL Server, and allows the user to make changes to the record.
It has 2 buttons: Save and Cancel.
It is shown as a pop-up, modal, dialog form, and it has a (Windows) Close button at the top right corner.
I've put VBA code to ask the user whether he wants to Save, Ignore or Cancel the close action.
But there are problems and it gives the aforementioned error if Cancel is clicked. There are also other problems, like, after the error occurs once, then any further commands (Save or Cancel or closing the form) don't work - I think this is because the VBA interpreter has halted due to the earlier error. Another complication is that arises - I now need to end the MS-Access process from Windows Task Manager, doing this and then restarting the database and then opening this form will give an error and the form won't load. When the form is then opened in Design mode, I can see the connection string for the form is saved in the Form's Record Source property (this happens only sometimes), and which looks something like this:
{ ? = call dbo.tbBeneficiary_S(?) }.
Here is my code:
Dim CancelCloseFlag As Boolean
Dim SavePrompt As Boolean
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim a As Integer
If SavePrompt Then
a = MsgBox("Do you want to save changes?", vbQuestion + vbYesNoCancel, "Changes made")
Select Case a
Case vbNo:
Me.Undo
CancelCloseFlag = False
Case vbYes:
'do nothing; it will save the changes
CancelCloseFlag = False
Case vbCancel:
Cancel = True
CancelCloseFlag = True
End Select
End If
End Sub
Private Sub Form_Dirty(Cancel As Integer)
SavePrompt = True
End Sub
Private Sub Form_Error(DataErr As Integer, Response As Integer)
If DataErr = 2169 Then
Response = acDataErrContinue
End If
End Sub
Private Sub Form_Load()
LoadBeneficiaryDetails
End Sub
Private Sub Form_Unload(Cancel As Integer)
If CancelCloseFlag Then
Cancel = True
End If
End Sub
Private Sub btCancel_Click()
If Me.Dirty Then
SavePrompt = True
End If
DoCmd.Close
End Sub
Private Sub btSave_Click()
SavePrompt = False
DoCmd.Close
End Sub
I'm stuck and would like to know how others go about this issue? Basically I want to offer the user the choice Save, Ignore, Cancel when the user attempts to close the form with either Cancel button or the (Windows) close button. If the user chooses Cancel, then it should just return to the form without changing or undoing any changes to the data. The solution may be simple but it escapes my overworked mind.
Thanks in advance!
Please try the following code - I tested against all six scenarios and the proper action is taken.
Option Compare Database
Option Explicit
Dim blnAction As Integer
Dim blnBeenThereDoneThat As Boolean
Private Sub Form_BeforeUpdate(Cancel As Integer)
If blnBeenThereDoneThat = True Then Exit Sub
blnBeenThereDoneThat = True
blnAction = MsgBox("Do you want to save changes?", vbQuestion + vbYesNoCancel, "Changes made")
Select Case blnAction
Case vbNo:
Me.Undo
Case vbYes:
'do nothing; it will save the changes
Case vbCancel:
Cancel = True
End Select
End Sub
Private Sub Form_Error(DataErr As Integer, Response As Integer)
If DataErr = 2169 Then
Response = acDataErrContinue
End If
End Sub
Private Sub Form_Load()
LoadBeneficiaryDetails
End Sub
Private Sub Form_Unload(Cancel As Integer)
If blnAction = vbCancel Then
blnBeenThereDoneThat = False
Cancel = True
End If
End Sub
Private Sub btCancel_Click()
If Me.Dirty Then
Form_BeforeUpdate (0)
End If
If blnAction = vbCancel Then
blnBeenThereDoneThat = False
Exit Sub
ElseIf blnAction = vbYes Then
DoCmd.Close
Else
DoCmd.Close
End If
End Sub
Private Sub btSave_Click()
If Me.Dirty Then
Form_BeforeUpdate (0)
End If
If blnAction = vbCancel Then
Exit Sub
Else
DoCmd.Close
End If
End Sub