Button to check for missing values in a MainForm and Subforms in MS Access - vba

New to Access (still), have only basic VBA skills.
I've got 3 subforms (subfrm_PackingSteps1 , subfrm_MetalDetection and subfrm_Weights - the first 2 are continuous and the other one is single form) within a main form (frm_daily_packing_record) that users go through and input data. The user should be able to input data in no particular order, and only at the end there would be a button to confirm that the user is ready to save this form.
I'd like to have this button on the main form that checks each control (in main form and subforms) for empty values. I found and adjusted a code to check the recordset of one of the continuous forms (see below), but I can't figure out:
how to include a code that checks each control instead of manually adding all of them (I've used a function before that utilises the Tag property, but can't add it to this)
how to keep the button in the main form while checking the controls/recordsets in the other subforms.
Thanks in advance.
Private Sub ConfirmBtn_Click()
Dim blnSuccess As Boolean
blnSuccess = True
Me.Recordset.MoveFirst
Do While Not Me.Recordset.EOF
If IsNull(Me.pc) Or IsNull(Me.InnerP) Then
blnSuccess = False
Exit Do
End If
Me.Recordset.MoveNext
Loop
If blnSuccess = True Then
MsgBox "You may proceed to save this record"
Else
MsgBox "You still have some empty fields to fill in!", vbCritical + vbOKOnly, "Empty Fields!"
End If
End Sub

I personally don't like this because it is too code-heavy and can easily break when the form is modified.
Instead may I suggest doing it slightly different, for each field have vba code .ondirty or .onupdate and do the validation checking right as the user is actually on that field.
This has 2 benefits, it is creating the validation when you are creating each form field and it STOPS the user right when their first mistake or bad data is entered. The last thing I want is to enter 50 fields, scroll to the bottom, submit fails then scroll back and try to find where the mistake was. If validation is done while the user it doing the actual data entry, when you get to the bottom you should have valid data and the submit should succeed without further testing.
Less code to debug and timely messages to the user if an error is caught!

Related

How to handle Access "Run-Time Error 3021 - No current record" after DoCmd.Requery?

I have been having a quite annoying issue on my access project.
It is an Access 2007 - 2016 file.
My database has two queries that I intend to use to filter data to feed combo-boxes.
On one of my forms I have done that with success. The first list is fed from a table, and the succeeding ones are fed by filtering their respective table based on the previous list selection.
Here is a screenshot of my form that worked out.
And here is part of the code that goes with it:
Private Sub frm01ListSetor_Click()
DoCmd.Requery (qry01_frm01ListArea)
Me![frm01ListArea] = Null
DoCmd.Requery (qry02_frm01ListEquip)
Me![frm01ListEquip] = Null
Me![frm01TextID] = Null
End Sub
Private Sub frm01ListArea_Click()
DoCmd.Requery (qry02_frm01ListEquip)
Me![frm01ListEquip] = Null
Me![frm01TextID] = Null
End Sub
Here are the queries that goes along with the code above:
qry01_frm01ListArea
SELECT tblAreas.ID_Area, tblAreas.NomeArea
FROM tblAreas
WHERE (((tblAreas.SetorArea)=[Forms]![frm01_AddEquip]![frm01ListSetor]));
qry02_frm01ListEquip
SELECT tblEquipamentos.ID_Equipamento, tblEquipamentos.NomeEquipamento
FROM tblEquipamentos
WHERE (((tblEquipamentos.SetorEquipamento)=[Forms]![frm01_AddEquip]![frm01ListSetor]) AND ((tblEquipamentos.AreaEquipamento)=[Forms]![frm01_AddEquip]![frm01ListArea]))
ORDER BY tblEquipamentos.ID_Equipamento;
The code above works just fine. It filters data to previous selection accordingly and it also clears the data and selection of the "righter" lists every time another value is selected on the "lefter" ones.
So that was a form I created to help me out on populating my equipment database.
Let us get to the problematic twin now:
I created another form for Maintenance Orders of these equipment.
This one must be more user friendly since other people will use it. Therefore I used Combo-boxes for value selection instead of List Boxes. I say this before hand because it is the only thing I could notice that differs the new form from the one above.
Here I have this:
Screenshot of troubled form
After the expanded Combo-box on image 2 is selected I should run the following code:
Private Sub frm02SetorOM_Click()
DoCmd.Requery (qry04_frm02CBArea)
Me![frm02AreaOM] = Null
DoCmd.Requery (qry05_frm02CBEquip)
Me![frm02EquipamentoOM] = Null
End Sub
Private Sub frm02AreaOM_Change()
DoCmd.Requery (qry05_frm02CBEquip)
Me![frm02EquipamentoOM] = Null
End Sub
It is basically the very same thing I have done on the first form but with different variables.
But I get a "Run-time error 3021: No current record" every time I select a value on my "Setor" field.
The crash happens at the "DoCmd.Requery (qry04_frm02CBArea)" line.
Here is the query for this form's Area field (qry04_frm02CBArea):
SELECT tblAreas.ID_Area, tblAreas.NomeArea
FROM tblAreas
WHERE (((tblAreas.SetorArea)=[Forms]![frm02_SubmitOM]![frm02SetorOM]));
But the thing that is confusing me the most is that when I click "End" on the Run-time error dialog box, my Area combo-box - that was empty before - even with the error gets the proper options like if it actually "requeried".
How can I fix this issue?
Thank you in advance.
Btw, this is my first Access project so please consider that on the response.

MS Access will occasionally remove checkboxes from my Yes/No fields and replace them with 0 and -1

My new database is built using a variety of queries and tables. These tables and queries have two checkbox fields that are set for "Test" and "Approved". The way that these come into play is that I have buttons on one form called "ApprovalForm" that open up another form called "ViewForm". The goal was that "ViewForm would change its subform's source object every time one of these buttons is clicked. ApprovalForm closes itself first, then ViewForm opens, then Subform.SourceObject is updated to the query specified by whatever button was clicked.
Private Sub View_NonSize_APL_Click()
On Error GoTo View_NonSize_APL_Click_Err
DoCmd.Close acForm, ("ApprovalForm")
DoCmd.OpenForm ("ViewForm")
Forms!ViewForm!View_Subform.SourceObject = "Query.NonSize - APL View"
Forms!ViewForm!View_Subform.Form.Requery
Forms!ViewForm.Form.Requery
Forms.ViewForm.Caption = "NonSize - APL View"
View_NonSize_APL_Click_Exit:
Exit Sub
View_NonSize_APL_Click_Err:
MsgBox Error$
Resume View_NonSize_APL_Click_Exit
End Sub
With the process finished, the final result should be that the fields are populated by the query, which is looking at a table off on the side. The user has no access to the table itself, just that specific select query. However, in rare occasions, the checkboxes will not load correctly, instead displaying as 0s and -1s. What is peculiar about this is that when you click the button on "ViewForm" that leads back to "ApprovalForm" and click the same exact button AGAIN, the checkboxes load correctly.
My guess is that it has something to do with how "ViewForm" loads in, and due to it being a business project, the computer that it is working on is less than optimal. I tried to remedy the situation by using "Requery" and "Refresh" in the code to hopefully reload the process. I have also tried the cumbersome route of having the form close after being loaded and immediately reloading again. (Open the form, load its query, close the form, then open the form again.) That actually proved to ruin the entire process.
Is there anything I can do to counter this problem?

Error message in Access form with both manual and calculated data entries

my Access 2010 form is used to input data. Some fields manually (type in or choice from a dropdownlist), some other fields get precalculated values depending on the already input data. Additional code controls enabling or disabling input fields dependent from the input data (ensuring data consistency).
My problem: When I choose a value (from a dropdownlist) in a field then switch to the next field (any method: mouse/tab/code) and try to enter a value, I get an [erroneous] error message that "another user" (obviously my own VBA code) has modified this record and saved it before my own changes were saved. But everything is OK and the second trial to input data is successful.
I tried Me.Recalc and Me.Refresh at different positions in the code without eliminating this nasty error. How can I tell Access 2010 to save my input data in a field before starting running the code [MyPreviousField_AfterUpdate()] ?
docmd.RunCommand acCmdSaveRecord unfortunately does not work at all, as my problemativ fields are unbound. It's the mix of related bound and unbound fields which Access does not handle as one could expect. Disabling error messages or record lock, or even Me.Undo or Me.MyField1.Undo do not work at all either.
However, I now found a work-around myself. Note that simply setting the focus on other field may sometimes push Access to save the values then avoiding the erroneous error message, but this often fails. Following code works not always either but is practicable for only few changes in the form:
Dim MyFieldVal1 As Variant, MyFieldVal2 As Variant ', … [all unbound fields]
Private Sub MyField1_Change()
…
If Not IsNull(Me![MyField1]) Then MyFieldVal1 = Me![MyField1]
If Not IsNull(Me![MyField2]) Then MyFieldVal1 = Me![MyField2]
… ' same for all unbound fields on the form
Call SaveAllValues(Me.Name, Me.CurrentRecord)
…
… ' here all code to change any field but WITHOUT Me.Refresh
…
Me![MyField1] = MyFieldVal1
Me![MyField2] = MyFieldVal2
… ' same for all unbound fields on the form
Me.Refresh
End Sub
'===================================================
Sub SaveAllValues(ByVal FormName, ByVal CurRec)
DoCmd.GoToRecord acDataForm, FormName, acFirst
DoCmd.GoToRecord acDataForm, FormName, acGoTo, CurRec
End Sub
The whole procedure is tedious as above code must be implemented for each unbound field: MyField2_Change() etc. etc.
It worked correctly for quite a while, but after minor other changes at other places in the code, the errors appears reproducibly again ! Obviously the result depends on Access' last code compilation, sometimes leading to other erratic problems. Probably the module is corrupt (database repair does not correct anything). I have to live with the erroneous error or to begin designing a new form from scratch again…
Maybe it is just impossible to mix bound and unbound fields on the same form, one has no other way than to use subforms for the bound data ?
FINAL REPORT : It's just yet another MS Access bug !
I redesigned my form to a main form with a number of database fields and a subform with 3 unbound fields. This changes of course the navigation sequence between fields. The same error as previously described occurs each time one switches from an unbound field to another unbound field on the subform, then to a database field on the main form.
The problem is resolved by adding following lines at the end of each unbound field change procedure:
Private Sub MyUnboundField1_Change()
…
Me.Refresh
Me.Parent.Requery
End Sub

How to launch a Look up form, and return the value from a combo box

Hopefully I can explain what I want to do well enough...here it goes...
I have a data entry form...the user will be entering employeeIDs. Once in normal operation, most people will be entering only their own EmpID, and they should know it, so this won't be a big problem 99% of the time once this DB goes live.
However, I need some temps to enter historical data from paper sheets into the DB. These people will not know anyone else's EmpID. I'd like to set the Student field's OnDblClick event in the subform's datasheet to open a small form with a combo box. The combo box has a list of all Employee Names, and is bound to the EmpID. Once this user enters the name, and selects the person, I have a button they can click to return to the datasheet.
I can use a function to launch the form, no problem there. But how do I return the EmpID to the field in the datasheet that was double clicked?
When user double clicks in the Student field...I want the next form to appear, and then once they type in the name and select the correct person...and then click Found Them!...I need that bound value to return.
I'd love to say I have code to share right now...but the only code I have is to launch the look up form. I'm brain farting on how to pull the value back down.
The way to do this to launch your little dialog form as “acDialog”. This will cause the calling code to WAIT.
And then the “magic” part is when they click on “Found Them” you do NOT close the popup form, but simply set the form’s visible = false. This has the effect of the calling code that popped up this form that halted to continue (the form is kicked out of dialog mode when you do this). So now your calling code continues.
So your code will look like this:
Dim strF As String ' name of popup form
strF = "frmPopUp"
' open form, wait for user selection
DoCmd.OpenForm strF, , , , , acDialog
' if for is NOT open, then assume user hit cancel buttion
' (you should likly have a cancel button on the form - that cancel buttion will
' execute a docmd.close
If CurrentProject.AllForms(strF).IsLoaded = True Then
' grab the value of thee combbo box
strComboBoxValue = Forms(strF)!NameOfComboBox
DoCmd.Close acForm, strF
End If
As noted, the code behind the Found Them button DOES NOT do a close form, but sets forms visible = false (me.Visible = false), and this trick allows the calling code to continue at which point you can examine any value on the form. Remember to then close the form after you grab the value.
It looks like your data table is in a subform so there is a little more work but it does not have to be as complex as the above solution if you don't want it to be. #Andre451 was close but you need the extra step of identifying the form and subform. For the purpose of demonstration let's call the form Attendance and subform Entry then I'll call the second form LookUp. So the code for your double click in the subform field will of course look something like this :
Private Sub Student_DblClick(Cancel As Integer)
DoCmd.OpenForm "LookUp"
End Sub
You really don't need anything else fancy there. For the button on "LookUp" you will put this:
Private Sub Command2_Click()
Forms![Attendance]![Entry].Form![Student] = Forms!Lookup!Student
DoCmd.Close acForm, "LookUp"
End Sub
And that should get you what you want without any overhead or having to leave any ghosts open.

Access VBA Spell Check One Field of a Subform

I am trying to make a memo field be spell checked when it leaves the field, and when it leaves the subform to the main form. I want to have this done automatically without having a click button, as I need the data to be as accurate and error-free as possible.
In the main form I have used this code to spell check a title field once you move off the field.
Private Sub DetailedTitle_Exit(Cancel As Integer)
'This code works to spellcheck the title after leaving.
With Me!DetailedTitle
If Len(.Value) > 0 Then
DoCmd.SetWarnings False
.SelStart = 1
.SelLength = Len(.Value)
DoCmd.RunCommand acCmdSpelling
.SelLength = 0
DoCmd.SetWarnings True
End If
End With
End Sub
This works well, as users will 99% of the time moving from this field to another field in the main form. This does not work when I use in on the subform even when I use the on exit field event AND the on exit subform event. It seems to work, but if you click around it will actually give an error. I wasn't smart enough to note the error, and I have since removed the code.
I would also not be opposed if I could get it to loop thought the subform, as it is a continuous form, but only that one field.
Any advice or tips would be welcome. I just recently learned of the Do.Cmd.RunCommand acCmdSpelling, but there seems to be a lack of content in regards to subforms. Thanks.
I did some research: http://www.pcreview.co.uk/threads/run-the-spell-check-through-code.1636292/
One user mentions that the control you want to check has to be in focus.
Sub subformMemo_OnExit()
Me.subformMemo.setfocus
DoCmd.RunCommand acCmdSpelling
End Sub
On the other hand this code creates the problem that you cannot leave the control because you will always setfocus on it again.
Does this help?