Docmd.Close not closing the access form - ms-access

I am experiencing a problem with vb in access. There is main form (say it parentForm), which has two buttons that trigger two different forms (say it childForm1 and childForm2). Both child forms perform checks on their Load events. If a condition fails, the childForm has to close. The problem is that in childForm1, the code works properly, in the childForm2 something goes completely wrong.
It seems that the close event is totally ignored. After the onLoad event, the process is carried out to the onCurrent event, which shouldn't happen! Below is the code of the onLoad event of childForm2.
Private Sub Form_Load()
On Error Resume Next
Dim db As Database
Dim rst As Recordset
Dim stDocName As String
stDocName = "childForm2"
closeEvent = False
Set db = CurrentDb
If a<> 0 And b<> 0 Then
Set rst = db.OpenRecordset("SELECT * FROM tbl1 WHERE Cust Like '*" & a & "*' AND Cust2 Like '*" & b & "*';")
If (rst.EOF Or rst.BOF) And IsLoaded(stDocName) Then
MsgBox ("No record found!")
rst.Close
SetWarnings = True
closeEvent = True
Me.SetFocus
DoCmd.Close acForm, stDocName, acSaveNo
End If
ElseIf a = 0 And b <> 0 Then
Set rst = db.OpenRecordset("SELECT * FROM tbl1 WHERE Cust2 Like '*" & b & "*';")
If (rst.EOF Or rst.BOF) Then
MsgBox ("No record found!")
rst.Close
DoCmd.Close acForm, stDocName
End If
End If
db.Close
End Sub
Also, I tried to use a global boolean variable (closeEvent in code), which is initialized to False and gets True, when the form must close. This variable is checked in the onCurrent event in order to close the form. However, when i debugged the code, the variable seems to lose its (True) value when passing from onLoad to OnCurrent event!
Any suggestion is more than appreciated.
Thanks in advance,
Maria

Use the Form_Open event instead of the Form_Loadevent.
Then, instead of closing the form (=Docmd.Close) use the built in Cancel argument to cancel the form's opening.
Private Sub Form_Open(Cancel As Integer)
If **condition not met** then
Cancel = True 'this stops the form from opening
End If
End Sub

Related

FormOpen Event procedure not triggered with command button, but trigged when switching from design to form view in MS Access

I have an MS Access database with a set of forms to enter vegetation data for a large monitoring project. I have one form called frmTransect with a button that opens a second form called frmLPI which is set up as an unbound main form with a subform called frmLPIDetail bound to a sql server database table. The main form has just two unbound fields, DataObs and DataRec, both of which are comboboxes. These two field are set up with an AfterUpdate event procedure to populate their corresponding fields in the subform, Data_observer and Data_recorder. This works perfectly. I wanted to have the unbound fields autopopulate with the last value in the subform of Data_observer and Data_recorder when the form is lauched again. To do this I used a FormOpen event procedure. Below is the code:
Private Sub Form_Open(Cancel As Integer)
Me.TransectOID = Me.OpenArgs
Dim rs As DAO.Recordset
Set rs = Me!frmLPIDetail.Form.RecordsetClone
If rs.RecordCount > 0 Then
If Not rs.BOF Then
rs.MoveLast
rs.MovePrevious
End If
If Not IsNull(rs!Data_recorder.Value) Then
Me.DataRec.Value = rs!Data_recorder.Value
Me.frmLPIDetail.Form.Data_recorder.DefaultValue = """" & Me.DataRec.Value & """"
End If
If Not IsNull(rs!Data_observer.Value) Then
Me.DataObs.Value = rs!Data_observer.Value
Me.frmLPIDetail.Form.Data_observer.DefaultValue = """" & Me.DataObs.Value & """"
End If
rs.MoveLast
rs.MoveFirst
While Not rs.EOF
rs.Edit
rs!Data_recorder.Value = Me.DataRec.Value
rs!Data_observer.Value = Me.DataObs.Value
rs.Update
rs.MoveNext
Wend
End If
rs.Close
Set rs = Nothing
Me.Dirty = False
End Sub
Here is where things get weird. When I click the command button on frmTransect, frmLPI opens, but the FormOpen event procedure above doesn't get launched. However, if I switch into design view, and then back into Form View, it does trigger, and works as intended! How can I get this event procedure to launch when I open the frmLPI using the command button in frmTransect? Any help would be much appreciated.
And it turned out it was as simple as adding a Me.Refresh and Me.Requery to my code block:
Private Sub Form_Open(Cancel As Integer)
Me.TransectOID = Me.OpenArgs
Me.Refresh
Me.Requery
Dim rs As DAO.Recordset
Set rs = Me!frmLPIDetail.Form.RecordsetClone
If rs.RecordCount > 0 Then
rs.MoveLast
rs.MovePrevious
If Not IsNull(rs!Data_recorder.Value) Then
Me.DataRec.Value = rs!Data_recorder.Value
Me.frmLPIDetail.Form.Data_recorder.DefaultValue = """" & Me.DataRec.Value & """"
End If
If Not IsNull(rs!Data_observer.Value) Then
Me.DataObs.Value = rs!Data_observer.Value
Me.frmLPIDetail.Form.Data_observer.DefaultValue = """" & Me.DataObs.Value & """"
End If
rs.MoveLast
rs.MoveFirst
End If
rs.Close
Set rs = Nothing
Me.Dirty = False
End Sub

Move to another record via combobox doesn't work in some circumstances

I have two forms: ‘frmClient’, (which has a subform that lists applicants), and ‘frmDisclosure’, which shows details of applicants. On frmClient there is a command button that opens a specified record in frmDisclosure. The procedure is Private Sub Command10_Click() - see below. This works.
The problem is that once in frmDisclosure via frmClient, it is not possible to move to another record. The procedure for opening another record in frmDiscloure is in a combobox control: Private Sub ComboFind_AfterUpdate().
This normally works, but it never works if frmDiscloure has been opened via frmClient. I have tried ‘requery’ and ‘refresh’ in various situations, and have tried closing frmClient once frmDisclosure is open. None of this works. If I want to get to a different record, the only solution I have at present is to close frmDisclosure and reopen it.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Private Sub Command10_Click()
If NumForms > 0 Then
DoCmd.OpenForm "frmDisclosure"
Forms!frmDisclosure.FilterOn = False
DoCmd.OpenForm "frmDisclosure", acNormal, "", "[DiscPK]=" & Me.DiscPK, , acNormal
Else
DisplayMessage ("No form ref for this application.")
Exit Sub
End If
End Sub
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Private Sub ComboFind_AfterUpdate()
Dim rs As Object
Set rs = Me.RecordsetClone
rs.FindFirst "[DiscPK] = " & Str(Nz(Me![ComboFind], 0))
If Not rs.EOF Then Me.Bookmark = rs.Bookmark
End Sub
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
frmDisclosure is opened to a single record, there are no other records to navigate. The RecordsetClone has only one record, so of course code won't find any others. Turn off the filter first:
Private Sub ComboFind_AfterUpdate()
Me.FilterOn = False
With Me.RecordsetClone
.FindFirst "[DiscPK] = " & Nz(Me.ComboFind, 0)
If Not .NoMatch Then Me.Bookmark = .Bookmark
End With
End Sub
As you can see, declaring and setting a recordset object variable is not required. .EOF would probably work just as well, I have just always used NoMatch. This will set focus to record, not filter the form.
If you prefer to display single record, then set the Filter property.
Private Sub ComboFind_AfterUpdate()
Me.Filter = "DiscPK=" & Nz(Me.ComboFind, 0)
End Sub

DoEvent() Returns 0 BUT Run-time Error 2585 This action can't be carried out while processing a form or report event

This code was running without a hitch, but now getting Error 2585.
I have looked at Gustav's answer and Gord Thompson's answer but unless I am missing something (quite possible!) the first does not work and the second seems inapplicable. I saw on another site a suggestion that there might be a duplicate record ID, but I check for that possibility.
I put a call to DoEvent() in response to this error but it returns zero. I also wait for 10 seconds to let other processes run. Still receive the error.
Private Sub SaveData_Click()
Dim myForm As Form
Dim myTextBox As TextBox
Dim myDate As Date
Dim myResponse As Integer
If IsNull(Forms!Ecoli_Data!DateCollected.Value) Then
myReponse = myResponse = MsgBox("You have not entered all the required data. You may quit data entry by hitting 'Cancel'", vbOKOnly, "No Sample Date")
Forms!Ecoli_Data.SetFocus
Forms!Ecoli_Data!Collected_By.SetFocus
GoTo endOfSub
End If
If Me.Dirty Then Me.Dirty = False
myDate = Me.DateCollected.Value
Dim yearAsString As String, monthAsString As String, dayAsString As String, clientInitial As String
Dim reportNumberText As String
reportNumberText = Me!SampleNumber.Value
Debug.Print "reportNumberText = " & reportNumberText
Debug.Print "CollectedBy Index: " & Me!Collected_By & " Employee Name: " & DLookup("CollectedBy", "Data_Lookup", Me.Collected_By)
Dim whereString As String
whereString = "SampleNumber=" & "'" & reportNumberText & "'"
Debug.Print whereString
On Error GoTo errorHandling
DoCmd.OpenReport "ECOLI_Laboratory_Report", acViewPreview, , whereString
DoCmd.PrintOut
DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo
Dim eventsOpen As Integer
eventsOpen = DoEvents()
Debug.Print "Number of Open Events = " & DoEvents()
Dim PauseTime, Start, Finish, TotalTime
PauseTime = 10 ' Set duration.
Start = Timer ' Set start time.
Do While Timer < Start + PauseTime
DoEvents ' Yield to other processes.
Loop
Finish = Timer ' Set end time.
TotalTime = Finish - Start ' Calculate total time.
myResponse = MsgBox("Processing Report Took " & TotalTime & " seconds.", vbOKOnly)
myResponse = MsgBox("Do you want to add more data?", vbYesNo, "What Next?")
If myResponse = vbYes Then
DoCmd.Close acForm, "ECOLI_Data", acSaveYes
Error Generated By Line Above and occurs whether response Y or N to MsgBox.
DoCmd.OpenForm "ECOLI_Data", acNormal, , , acFormAdd
DoCmd.GoToRecord , , acNewRec
Else
DoCmd.Close acForm, "ECOLI_Data", acSaveYes
End If
Exit Sub
errorHandling:
If Err.Number = 2501 Then
myResponse = MsgBox("Printing Job Cancelled", vbOkayOnly, "Report Not Printed")
ElseIf Err.Number = 0 Then
'Do nothing
Else
Debug.Print "Error Number: " & Err.Number & ": " & Err.Description
myResponse = MsgBox("An Error occurred: " & Err.Description, vbOKOnly, "Error #" & Err.Number)
End If
If Application.CurrentProject.AllForms("ECOLI_Data").IsLoaded Then DoCmd.Close acForm, "ECOLI_Data", acSaveNo
If Application.CurrentProject.AllReports("ECOLI_Laboratory_Report").IsLoaded Then DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo
endOfSub:
End Sub
Any idea on what am I missing here? Thanks.
I can't replicate the problem, but the following might help:
I assume you run into troubles because you're closing and opening the form in the same operation. To avoid doing this, you can open up a second copy of the form, and close the form once the second copy is open. This avoids that issue.
To open a second copy of the form:
Public Myself As Form
Public Sub CopyMe()
Dim myCopy As New Form_CopyForm
myCopy.Visible = True
Set myCopy.Myself = myCopy
End Sub
(CopyForm is the form name)
To close a form that may or may not be a form created by this function
Public Sub CloseMe()
If Myself Is Nothing Then
DoCmd.Close acForm, Me.Name
Else
Set Myself = Nothing
End If
End Sub
More information on having multiple variants of the same form open can be found here, but my approach differs from the approach suggested here, and doesn't require a second object to hold references and manage copies.
This line of code
`DoCmd.Close acForm, "ECOLI_Data", acSaveYes`
doesn't save the record you are on, it just saves any changes to the form design.
You should probably use
If Me.Dirty Then Me.dirty = False
to force a save of the current record if any data has changed.

Access not closed when added DoCmd.Close line

I have added DoCmd.Close acQuery, "Import", acSaveNo
And my access window doesn't close even with this line of code.
Option Compare Database
Option Explicit
Public Function Import()
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim intFile As Integer
Dim strFilePath As String
Dim intCount As Integer
Dim strHold
strFilePath = "C:\Transfer\FromSynapseTest\TEST.csv"
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("Import", dbOpenForwardOnly)
intFile = FreeFile
Open strFilePath For Output As #intFile
Do Until rst.EOF
If CDate(rst(3)) >= Date And rst(98) <> 0 Then
For intCount = 0 To rst.Fields.Count - 1
strHold = strHold & rst(intCount).Value & "|"
Next
If Right(strHold, 1) = "|" Then
strHold = Left(strHold, Len(strHold) - 1)
End If
Print #intFile, strHold
End If
rst.MoveNext
strHold = vbNullString
Loop
Close intFile
rst.Close
Set rst = Nothing
DoCmd.Close acQuery, "Import", acSaveNo
End Function
Since I'm calling the function by macro, I don't think I can do
Sub subToCloseForm
DoCmd.Close
End Sub
Also I have tried DoCmd.Close acQuery, " ", acSaveNo based on what I read http://www.blueclaw-db.com/docmd_close_example.htm : If you leave the objecttype and objectname arguments blank (the default constant, acDefault, is assumed for objecttype), Microsoft Access closes the active window
Any help would be greatly appreciated. Thank you.
You don't need code DoCmd.Close acQuery, "Import", acSaveNo at all. This command tries to close a query "Import", but you didn't open this query. You opened a recordset, based on this query and you closed the recordset correctly.
If you need to close the form with name "Import", use
DoCmd.Close acForm, "Import", acSaveNo
If you are looking to close Access completely, use:
Application.Quit
Your line of code DoCmd.Close acQuery, "Import", acSaveNo is not necessary as you are opening a recordset, not the query. rst.close and set rst = nothing is sufficient for memory management.
On a side note, I would recommend including an if statement for stepping through your recordset. If the recordset is blank, you will receive an error if left unchecked. Try inserting your for loop inside this if statement:
If not rst.eof and not rst.bof then
'for loop...
end if

VBA scripts no longer work after SQL migration

I recently migrated an Access database (that someone more knowledgeable than I designed) to MySQL, and linked the tables back into Access to use as a front end. Almost everything looks great. There is just one form and chunk of VBA code that doesn't seem to work. There is a form that should show drop down menus and controls, but is blank in form view. The form in design view and form view The VBA code that goes with the form is
Option Compare Database
Private Sub cmdPreviewPlate_Click()
'show user the new plate that is to be added to tblPCRsamples
On Error GoTo Err_cmdPreviewPlate_Click
'check whether boxes are blank
Dim bolBlank As Boolean
bolBlank = False
If IsNull(Me.Controls!cboChooseTemplatePlate) Then bolBlank = True
If IsNull(Me.Controls!cboChooseLocus) Then bolBlank = True
If IsNull(Me.Controls!txtEnterDate) Then bolBlank = True
If bolBlank = False Then
'enable the Add button
Me.Controls!cmdAddPlate.Enabled = True
'generate the unique PCRplate from the template plate number and locus
' using the global variable GstrPCRPlateName so that the queries can add the plate name to both tables
GstrPCRPlateName = Me.Controls!cboChooseTemplatePlate.Value & "_" & Me.Controls!cboChooseLocus
'check: does this PCRplate already exist in tblPCRplates?
Dim dbs As Database
Dim rst As Recordset
Dim bolDone As Boolean
Dim bolNameExists As Boolean
bolDone = False
bolNameExists = False
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("tblPCRplates", dbOpenDynaset)
rst.MoveFirst
Do Until bolDone = True
'does the new plate name automatically generated here = the value of PCRplate in the current record?
If GstrPCRPlateName = rst![PCRPlate] Then
bolNameExists = True
bolDone = True
End If
rst.MoveNext
If rst.EOF Then bolDone = True
Loop
'if the name already exists, make a new name by appending _ and the date
If bolNameExists = True Then
GstrPCRPlateName = GstrPCRPlateName & "_" & Me.Controls!txtEnterDate
End If
'set the value for the Locus
GstrGetLocus = Me.Controls!cboChooseLocus
'open the select query to show user what they're going to add to the PCR plates & samples tables
Dim stDocName As String
stDocName = "qryNewPCR_1SelectTemplatePlate"
DoCmd.OpenQuery stDocName, acNormal, acReadOnly
Else
'if user left fields blank (except page number, that can be blank), show an error message
MsgBox "Choose/enter values for all the boxes"
End If
Exit_cmdPreviewPlate_Click:
Exit Sub
Err_cmdPreviewPlate_Click:
MsgBox Err.Description
Resume Exit_cmdPreviewPlate_Click
End Sub
Private Sub cmdAddPlate_Click()
'add this new plate to tblPCRplates and tblPCRsamples
On Error GoTo Err_cmdAddPlate_Click
'add the new plate to tblPCRplates
Dim stDocName As String
stDocName = "qryNewPCR_2AppendPlate"
DoCmd.OpenQuery stDocName, acNormal, acEdit
'run the query to append the samples to tblPCRsamples
stDocName = "qryNewPCR_3AppendSamples"
DoCmd.OpenQuery stDocName, acNormal, acEdit
'open frmPCRSamples to show the new plate has been added
stDocName = "frmPCRSamples"
DoCmd.OpenForm stDocName, acFormDS
Exit_cmdAddPlate_Click:
Exit Sub
Err_cmdAddPlate_Click:
MsgBox Err.Description
Resume Exit_cmdAddPlate_Click
End Sub
So my question is, should the linked tables be causing errors? Is there something I can amend to say that they are linked? Or am I barking up the wrong tree?
Thanks for your help. I know nothing of VBA (I mean, I can follow along) and have been tasked to destroy, I mean...admin...this database. This is what happens when you give biologists computers ;-) Even just some good resources would help a great deal.
The happens when your RecordSource of the form returns zero records and the form or record source does not allow adding new records.
Check the record source (table, query, or SQL string) and run it manually to see if it returns records.