Access 2007 VBA DoCmd.Close not working - vba

I know this is probably a stupid question, but you know what they say. I have VBA in an Access Database with commands for On Click. Essentially it is a form with a combo box and timestamp for user login. Once the button is clicked a data entry form will load dependent upon which name is selected from the Combo Box. I would like for the Login Form to close once the data entry form has opened. The problem is that no matter where I put the DoCmd.Close the stupid form won't CLOSE!
In case it matters this form is set to open automatically when a user opens the database.
Below is the VBA for the Event Procedure associated with the button.
Option Compare Database
Private Sub TimeInButton_Click()
Dim strLoginForm As String
If Me.AgentCombo = "Amber" Then
strForm = "frmCustomersAmber"
ElseIf Me.AgentCombo = "Amanda" Then
strForm = "frmCustomersAmanda"
ElseIf Me.AgentCombo = "Brett" Then
strForm = "frmCustomersBrett"
ElseIf Me.AgentCombo = "Marcus" Then
strForm = "frmCustomersMarcus"
ElseIf Me.AgentCombo = "Terrah" Then
strForm = "frmCustomersTerrah"
End If
'------------------------------------------------------------
' TimeInButton_Click
'
'------------------------------------------------------------
On Error GoTo TimeInButton_Click_Err
On Error Resume Next
DoCmd.GoToRecord , "", acNewRec
If (MacroError <> 0) Then
Beep
MsgBox MacroError.Description, vbOKOnly, ""
End If
DoCmd.OpenForm strForm
TimeInButton_Click_Exit:
Exit Sub
TimeInButton_Click_Err:
MsgBox Error$
Resume TimeInButton_Click_Exit
End Sub

DoCmd.Close takes optional arguments that will make it much more reliable. For example,
DoCmd.Close acForm, "MyFormName"

Related

How to execute code when user closes form?

I want a msg box to appear if certain fields are empty on close.
Private Sub Close_Click()
If IsNull(Me.startDate) Then
MsgBox “You are in Phase 1”
End If
End Sub
I want the pop up to appear when user clicks the exit x. I tried OnClose. Right now the code is attached to and works via a button.
I’d like the code to be executed when the user closes the form.
Edit New Code:
Private Sub Exit_Click ()
If IsNull(Me.startDate) Or IsNull(Me.stepOneA) Or IsNull(Me.stepOneB) Then
MsgBox “You are in Step I”
DoCmd.Close
ElseIf IsNull(Me.stepTwoA) or IsNull(Me.stepTwoB) or IsNull(stepTwoC)
MsgBox “You are in Step II”
DoCmd.Close
Else
DoCmd.Close
EndIf
End Sub
You can use the UnLoad event for this:
Private Sub Form_Unload(Cancel As Integer)
Cancel = IsNull(Me.startDate)
If Cancel = True Then
MsgBox "You are in Phase 1."
End If
End Sub

MS Access VBA call sub works on the first pass but not on the second

I have hit a wall and I am completely at a loss.
So I have a Form in MS Access. In it I have a single text box and a single button. When I type in a number in the text box and then click the button it opens a public sub which then runs a few queries, updates the database, displays a text box and then clears out the text box. This all works perfectly.
My issue is trying to do the exact same thing with hitting enter in the text box. The strangest thing is that the code works fine right after I open up the form, but all subsequent attempts give the following error until I close the form and reopen it:
Data type mismatch in criteria expression.
For the life of me I cannot figure out why it does what I want the first time, then falls apart on me.
Here is the complete VBA code for reference:
Option Compare Database
Public Sub Cut_Update()
On Error GoTo Cut_Update_Err
DoCmd.OpenQuery "UPDATE_WIP_Cut", acViewNormal, acEdit
DoCmd.OpenQuery "UPDATE_LastRun", acViewNormal, acEdit
MsgBox "Database Updated"
[Forms]![Portal_02_Cut]![WO_Num].Value = ""
Cut_Update_Exit:
Exit Sub
Cut_Update_Err:
MsgBox Error$
Resume Cut_Update_Exit
End Sub
'------------------------------------------------------------
' Return in Textbox
'
'------------------------------------------------------------
Private Sub WO_Num_KeyUp(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
Call Cut_Update
Me.Refresh
End If
End Sub
'------------------------------------------------------------
' Command2_Click
'
'------------------------------------------------------------
Private Sub Command2_Click()
Call Cut_Update
End Sub
The only thing you do in between the calls in the form is:
[Forms]![Portal_02_Cut]![WO_Num].Value = ""
So, try with either:
[Forms]![Portal_02_Cut]![WO_Num].Text = ""
or:
[Forms]![Portal_02_Cut]![WO_Num].Value = Null
My only guess is that the update is trying to update with a non numeric value.
Let me know
Option Compare Database
Public Sub Cut_Update()
On Error GoTo Cut_Update_Err
'' Make sure it is numeric
If IsNumeric([WO_Num].Value) Then
DoCmd.OpenQuery "UPDATE_WIP_Cut", acViewNormal, acEdit
DoCmd.OpenQuery "UPDATE_LastRun", acViewNormal, acEdit
MsgBox "Database Updated"
[Forms]![Portal_02_Cut]![WO_Num].Value = ""
End If
Cut_Update_Exit:
Exit Sub
Cut_Update_Err:
MsgBox Error$
Resume Cut_Update_Exit
End Sub
'------------------------------------------------------------ ' Return in Textbox '
'------------------------------------------------------------
Private Sub WO_Num_KeyUp(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
Call Cut_Update
Me.Refresh
End If
End Sub
'------------------------------------------------------------ ' Command2_Click '
'------------------------------------------------------------
Private Sub Command2_Click()
Call Cut_Update
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

Updating/adding entry to table only when question is answered?

I'm setting up a database in MS Access 2013, and want to ask the user a yes/no if they want to save or discard their non-saved record or edit before navigating away from the current record in my Access form.
The user should not be met with the question if pressing either the "add record" or "save" buttons.
Can someone point to where my problematic code is / or what I need?
Also, I'm new to Access, so please be gentle.
I have tried a few different guides or other answers around the web, but haven't gotten exactly to where I want to be.
My code is as such (cbotxt_Change and Form_Load relate to other parts of the form)
Private blnGood As Boolean
Option Compare Database
Private Sub cbotxt_Change()
Me.txt1.Value = Me.test1.Column(2)
Me.txt2.Value = Me.test1.Column(3)
Me.txt3.Value = Me.test1.Column(4)
End Sub
Private Sub Form_Load()
DoCmd.GoToRecord , , acNewRec
End Sub
Private Sub button_addRecord_Click()
blnGood = True
DoCmd.GoToRecord , , acNewRec
blnGood = False
End Sub
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim strMsg As String
If Not blnGood Then
strMsg = "want to abort?"
If MsgBox(strMsg, vbYesNo + vbQuestion, "Yes") = vbYes Then
Me.Undo
Else
Yes = True
End If
End If
End Sub
Using the code above, "want to abort?" is asked whenever the user is attempting to navigate away from the current record + when "add record" or "save" buttons are pressed. If the user answers "No", then the entry will save and the action in question be performed, except the "add record" button, which only seems to save now, not add a new record.
Seems a little convoluted to me. Try with:
Private Sub button_addRecord_Click()
DoCmd.GoToRecord , , acNewRec
End Sub
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim strMsg As String
strMsg = "want to abort?"
If MsgBox(strMsg, vbYesNo + vbQuestion, "New Entry") = vbYes Then
Cancel = True
Me.Undo ' or let the user press Escape.
End If
End Sub

Access Required Fields Before Exiting Form

I have this BeforeUpdate code to check if certain fields are filled out. These fields are required and must be filled or the record shouldn't save. If other fields have been filled without the ID and Staff field, then the message box prompts pop up (These are required fields, etc.).
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Nz([ID], "") = "" Then
MsgBox "The ID field is required.", vbExclamation, "Required Field"
Cancel = True
End If
If Nz([Staff], "") = "" Then
MsgBox "Staff field is required.", vbExclamation, "Required Field"
Cancel = True
Me.[Staff].SetFocus
End Sub
I have a 'Close Form' button as follows:
Private Sub CmdCloseForm_Click()
DoCmd.Close , ""
End Sub
When this button is clicked, I get the warning that the fields aren't filled, but then the form closes. I want a Yes/No message box asking the user to see if they would still like to close the form or not. I've made a Yes/No messagebox in the BeforeUpdate sub. However it doesn't stop the sub CmdCloseForm.
Is there a way to create a messagebox to confirm if the user wants to exit the form?
For example:
If MsgBox("Would you like to close the form still? Changes won't be saved.", vbYesNo + vbQuestion, "Warning") = vbNo Then
Exit Sub
End If
If I put the above Msgbox into the CmdCloseForm function, it prompts the user before letting them know that they're missing the ID/Staff fields.
I came about this solution by Mr. Craig Dolphin and it worked for me.
The way he approached is to have a generic validation function that is saved in a general purpose module (ie not in a form module).
Public Function validateform(myform As Form) As Boolean
'returns true if all required fields have data, or false if not.
'It will also create a popup message explaining which fields need data
Dim boolresponse As Boolean
Dim strError As Variant
Dim ctl As Control
boolresponse = True
strError = Null
With myform
For Each ctl In .Controls
With ctl
If .Tag = "required" Then
If .Value & "" = "" Then
boolresponse = False
strError = (strError + ", ") & .Name
End If
End If
End With
Next ctl
End With
If strError & "" <> "" Then MsgBox "The following information must be entered first: "
& strError, vbInformation
validateform = boolresponse
End Function
Then, for any fields that are absolutely required, you just set the Tag property of the control to 'required'
You can then, for example, call the function from the onclick event of the 'save' button or 'close' button.
Private Sub Command5_Click()
On Error GoTo Err_Command5_Click
If Me.PrimaryID & "" <> "" Then
If validateform(Me) Then DoCmd.Close
Else
DoCmd.Close
End If
Exit_Command5_Click:
Exit Sub
Err_Command5_Click:
MsgBox Err.Description
Resume Exit_Command5_Click
End Sub
this essentially checks to see if the auto pk field has a value indicating that the record has been created. If it has, then it validates the required fields. If not, it closes without checking. If the record has been created, it validates the form and only closes if all the required fields are filled in. If more data is required, then it pops up a message reminding the user which fields to fill in.
The nice part of this is that you can set conditional requirements using the vba to set the tag property of certain controls to required if another field is updated to a value that you want to trigger an additional requirement. Of course, if you do that then you also need to initialize those tag value in the on_current event for when you switch records.
Many thanks to Mr. Craig Dolphin
Since you want to show consecutive pop-ups, cancel the auto-update altogether and validate on Close.
If validation is successful save the record, if not notify the user.
Private Sub Form_BeforeUpdate(Cancel As Integer)
Cancel = True 'cancel auto-update
End Sub
'Validate and either Save or Close
Private Sub CmdCloseForm_Click()
If Me.Dirty Then
If IsFormValidated Then
DoCmd.RunCommand acCmdSaveRecord
Else
If MsgBox("Would you like to close the form still? Changes won't be saved.", vbYesNo + vbQuestion, "Warning") = vbNo Then Exit Sub
End If
End If
DoCmd.Close acForm, Me.Name, acSavePrompt
End Sub
'Validation
Private Function IsFormValidated() As Boolean
IsFormValidated = True 'assume all is in order
If Nz([ID], "") = "" Then
MsgBox "The ID field is required.", vbExclamation, "Required Field"
IsFormValidated = False
End If
If Nz([Staff], "") = "" Then
MsgBox "Staff field is required.", vbExclamation, "Required Field"
Me.[Staff].SetFocus
IsFormValidated = False
End If
End Function