MS Access: Looping through subform records causes Error '3021' - vba

I have a main form and a subform that displays several records. When a checkbox is checked on the main form, I want all "BoxLblTime" and "Material Arrived" fields on the subform to be updated. This is the vba code that is executed when the checkbox is clicked:
Private Sub MaterialArrived_chkbx_Click()
Dim temp As Variant
Dim tempString As String
Dim ctl As Control
'If checkbox is checked
If Forms("JOBS Form").Controls("MaterialArrived_chkbx").Value < 0 Then
Dim rs As Object
'Get records of subform
Set rs = Forms("JOBS Form").[Order Form].Form.Recordset
'Loop until end
Do While Not rs.EOF
rs.Edit
'Update the two fields
rs![Material arrived] = True
rs!BoxLblTime = Now()
rs.Update
rs.MoveNext
Loop
Set rs = Nothing
End If
End Sub
There is some unusual behavior when using this code:
1) When the checkbox on the main form is checked, the two fields are updated in the subform. But if I uncheck the checkbox on the subform and then recheck the main form checkbox, the subform checkbox stays unchecked.
2) When the checkbox on the main form is checked, the two fields are updated. But if I uncheck the checkbox on the subform, move to a new set of subform records (next or back) and then check the main form checkbox, I get the error: '3021' No current record.
Why is this unusual behavior happening?
EDIT:
Here is my code using the update query approach:
Private Sub MaterialArrived_chkbx_Click()
If Forms("JOBS Form").Controls("MaterialArrived_chkbx").Value < 0 Then
With CurrentDb().QueryDefs("Update Orders")
.Parameters("[Material Arrived]").Value = True
.Parameters("[BoxLblTime]").Value = Now()
.Execute dbFailOnError
End With
Forms("JOBS Form").Form.Requery
End If
End Sub
But I'm getting "Item not found in collection" error.

I would suggest an alternative approach.
Create an update query and pass a Boolean parameter indicating the material arrived value.
'Call update query
Private Sub MaterialArrived_chkbx_Click()
With CurrentDb().QueryDefs("Update Orders")
.Parameters("[prmMaterialArrived]").Value = Me.MaterialArrived_chkbx.Value
.Parameters("[prmID]").Value = Me!ID
.Execute dbFailOnError
End With
Me.[Order Form].Form.Requery
End Sub
'SQL
PARAMETERS [prmMaterialArrived] Bit, [prmID] Long;
UPDATE T
SET T.[Material arrived] = [prmMaterialArrived], T.BoxLblTime = Now()
WHERE (((T.ID)=[prmID]));

Related

prevent duplicates when passing values between two forms (with Args)

I have two forms: transfert Form with its subform and intransfert Form. I am using
DoCmd.OpenForm "intransfert", , , , acFormAdd, acDialog, Me!Text83
(where text83 is =[transfertasubform].[Form]![transfertadetailid] under
Private Sub Command78_Click()
in transfet form and
Private Sub Form_Load()
On Error Resume Next
If Me.NewRecord Then Me!trnrin = Me.OpenArgs
in intransfet form. intransfert form is based in transfertdetailquery. i wont to prevent passing text83 value more then one time
i tried to explain my problem and expect a help to prevent duplicates when used Arge
assuming trnrin is the name of a variable in your record source. assuming you mean that you want to avoid adding two records where trnrin has the same value and the user sent the same open args twice. assuming trnrin is also the name of a control in the detail section of the intransfert form.
'form load only runs when the form is opened so you have to close the form to pass new args
'but you can just move the same code to a button or whatever
Private Sub IntransferForm_Load()
If Len(Me.OpenArgs) > 0 Then
Me.txtBoxintheHeader = Me.OpenArgs 'the load event is the right place to set controls
'most of this code is to check if there is already an instance where trnrin = the OpenArgs in the record source
Dim lookedupArgs As String
lookedupArgs = Nz(lookedupArgs = DLookup("trnrin", "MyTable", "trnrin = " & "'" & Me.OpenArgs & "'"), "ValuethatisneveranArg")
If lookedupArgs = "ValuethatisneveranArg" Then
'Debug.Print "trnrin = '" & Me.OpenArgs & "'" 'note the string delimiters
'Me.trnrin = Me.OpenArgs 'this surprisingly works but will break easily and doesn't handle complex cases
Dim rs As Recordset
Set rs = Me.Recordset 'if recordset is bound to a table then table will also be updated.
'you can also bind to the table directly but you may need to call me.requery to show the changes
rs.AddNew
rs!trnrin = Me.OpenArgs
rs.Update
End If
End If
End Sub

populating multiple fields in subform using combobox and AfterUpdate Event Prodcedure

I am creating a set of Access database form for entering vegetation data into a linked SQL Server data base. For one protocol, I have created a form 'frmLPI' for entering data from a vegetation monitoring method called Line-Point-Intercept. It is a form with a subform within it called 'frmLPIDetail' where individual counts of plant species get recorded. The main form has three unbound controls: [TransectOID], [DataRec], and [DataObs]. TransectOID is a unique id for each time we ran protocol. For each TransectOID, there are 30 locations where we sampled vegetation these have a hidden unique id in the subform called LPI_OID. The subform is linked to the main form by TransectOID. I want my users to be able to click the unbound [DataRec] and [DataObs] comboboxes in the main form, and have the corresponding fields in the subform autopopulate for all 30 records. I have figure out how to accomplish this for record in the subform but can't figure out how to do it for 30 records for each value of TransectOID in the Main form. Below is a screenshot of my form to help you visualize what I am after:
And here is the code I have come up with to get one record to autopopulate
Private Sub Form_Load()
Me.TransectOID = Me.OpenArgs
End Sub
Private Sub Form_Deactivate()
DoCmd.RunCommand acCmdSaveRecord
End Sub
Private Sub DataObs_AfterUpdate()
Me!frmLPIDetail.Form!Data_observer = Me!DataObs
Me.Dirty = False
End Sub
Private Sub DataRec_AfterUpdate()
Me!frmLPIDetail.Form!Data_recorder = Me!DataRec
Me.Dirty = False
End Sub
Any suggestions would be much appreciated
Since inserting multiple records at a time is desirable your question has been asked before but I couldn't find an answer that was particularly helpful so I will provide a more general answer than you asked for.
Access doesn't provide default forms for inserting multiple records. You have to code that yourself but the process is always pretty much the same.
figure out a normalized table structure for your data
figure what data you need to collect from the user for the multiple insert
add a button to the form and put the vba for the multiple insert in the click event
so here is 1 normalized table structure that might fit your data:
Since I don't know where TransectionOID is coming from we let Access provide TransectionID as the primary key and assume TransectionOID is entered on another form. All the other information of interest is in the TransectionDetails table and there is no need to write a query to gather all the variables we will need into our forms record source to finish step 2. To get a jumpstart I selected the TransactionDetails table and used the create form wizard to make a tabular style form.
To finish step 2 we put controls in the header to collect the information from the user we will need and the start editing the form for user friendliness. For instance I delete the checkbox for TransectionDetailID in the details section and replace every other control with comboboxes. I normally replace the circled record selectors with comboboxes as well but here that may be confusing so I leave the record selectors to provide some search functionality. The final form looks like:
Finally, for step 3 we add the vba for the click event
Private Sub cmdInsert_Click()
Dim db As Database
Dim rs As Recordset 'using recordset because lower error rate than using sql strings
Set db = CurrentDb
Set rs = db.OpenRecordset("TransectionDetails")
Dim L As Integer
Dim S As Integer
If Not Me.lstLocations.ListCount = 0 Then 'if no locations are selected no records can be inserted
For L = 0 To Me.lstLocations.ListCount 'simple multiselect listbox version matters for the vba code
If Me.lstLocations.Selected(L) = True Then
For S = 0 To Me.lstSpecies.ListCount
If Me.lstSpecies.Selected(S) = True Then
rs.AddNew
rs!TransectionID = Me.cmbTransectionID
rs!Data_observer = Me.cmbData_observer
rs!Data_recorder = Me.cmbData_recorder
rs!TransectLocation = Me.lstLocations.Column(0, L) 'column gives you access to values in the listbox
rs!SpeciesID = Me.lstSpecies.Column(0, S)
If Not IsNull(Me.chkDead) Then 'chkDead is a triple value checkbox, this both avoids setting Dead to null and shows how to handle when the user doesn't set all controls
rs!Dead = Me.chkDead
End If 'chkdead
rs.Update
End If 'lstspecies selected
Next S
End If
Next L
End If
Me.Detail.Visible = True 'quick and dirty bit of style (detail starts invisible)
Me.Filter = "TransectionID = " & Me.cmbTransectionID 'more quick and dirty style filter to focus on inserted records
Me.FilterOn = True
'clean up
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
Private Sub cmdSelectAllLocations_Click()
Dim i As Integer
For i = 0 To Me.lstLocations.ListCount
Me.lstLocations.Selected(i) = True
Next
End Sub
Private Sub cmdSelectAllSpecies_Click()
Dim i As Integer
For i = 0 To Me.lstSpecies.ListCount
Me.lstSpecies.Selected(i) = True
Next
End Sub
Private Sub cmdSelectNoLocations_Click()
Dim i As Integer
For i = 0 To Me.lstLocations.ListCount
Me.lstLocations.Selected(i) = False
Next
End Sub
Private Sub cmdSelectNoSpecies_Click()
Dim i As Integer
For i = 0 To Me.lstSpecies.ListCount
Me.lstSpecies.Selected(i) = False
Next
End Sub
While Mazoula's answer is far more elegant, I discovered a quick and dirty way to accomplish what I was after using a While loop. Below is my code:
Private Sub Form_Load()
Me.TransectOID = Me.OpenArgs
End Sub
Private Sub Form_Deactivate()
DoCmd.RunCommand acCmdSaveRecord
End Sub
Private Sub DataObs_AfterUpdate()
Dim rs As DAO.Recordset
Set rs = Me!frmLPIDetail.Form.RecordsetClone
rs.MoveLast
rs.MoveFirst
While Not rs.EOF
rs.Edit
rs!Data_observer.Value = Me.DataObs.Value
rs.Update
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
Me.Dirty = False
End Sub
Private Sub DataRec_AfterUpdate()
Dim rs As DAO.Recordset
Set rs = Me!frmLPIDetail.Form.RecordsetClone
rs.MoveLast
rs.MoveFirst
While Not rs.EOF
rs.Edit
rs!Data_recorder.Value = Me.DataRec.Value
rs.Update
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
Me.Dirty = False
End Sub

Create a new record from existing one with changes to two fields in Access dB [duplicate]

Background:
I have a subform (datasheet) I update using a datasheet checkbox afterupdate event:
I clone the clicked record & Insert into the referenced table via an Insert Query
I modify the original record to differentiate from the Inserted record via an Update Query
To avoid RecordLock complaints, I have inserted: SendKeys "+{Enter}", True after each of the above to save the updates - is there a better way to do this??
Next I need to requery the subform to display the newly inserted record AND use a bookmark (?) to retain the cursor position of the original record (inserted record will be adjacent). Subform datasheet recordset is based on a query.
Question:
From within the subform's afterupdate event, using Forms![ParentForm].[SubForm].Form.Requery does not produce an error, but does open the code window with the line highlighted in Yellow.
Next attempt, from within the subform's afterupdate event, I have attempted to set focus to a control on the ParentForm BEFORE using Forms![ParentForm].[SubForm].Form.Requery, but I get a similar ~silent error~ as noted above.
What is the proper way to REQUERY a subform from within the same subform?
Thanks!
You are making it way too hard for yourself. Here is how to copy a record from a button click. No locks, no queries, and auto update of the form:
Private Sub btnCopy_Click()
Dim rstSource As DAO.Recordset
Dim rstInsert As DAO.Recordset
Dim fld As DAO.Field
If Me.NewRecord = True Then Exit Sub
Set rstInsert = Me.RecordsetClone
Set rstSource = rstInsert.Clone
With rstSource
If .RecordCount > 0 Then
' Go to the current record.
.Bookmark = Me.Bookmark
With rstInsert
.AddNew
For Each fld In rstSource.Fields
With fld
If .Attributes And dbAutoIncrField Then
' Skip Autonumber or GUID field.
ElseIf .Name = "SomeFieldToHandle" Then
rstInsert.Fields(.Name).Value = SomeSpecialValue
ElseIf .Name = "SomeOtherFieldToHandle" Then
rstInsert.Fields(.Name).Value = SomeOtherSpecialValue
ElseIf .Name = "SomeFieldToSkip" Then
' Leave empty or with default value.
ElseIf .Name = "SomeFieldToBlank" Then
rstInsert.Fields(.Name).Value = Null
Else
' Copy field content.
rstInsert.Fields(.Name).Value = .Value
End If
End With
Next
.Update
' Go to the new record and sync form.
.MoveLast
Me.Bookmark = .Bookmark
.Close
End With
End If
.Close
End With
Set rstInsert = Nothing
Set rstSource = Nothing
End Sub
If the button is placed on the parent form, replace Me with:
Me!NameOfYourSubformControl.Form
Between AddNew and Update you can modify and insert code to adjust the value of some fields that should not just be copied.

How to stop records from being overwritten on close

When I close the form, the current record overwrites the first record in the table. If I include "Me.Undo" just before closing the form then the data on the form is changed but not in the underlying table. How can I stop both of these from happening?
Private Sub Form_Load()
Dim strSelect As String
strSelect = "SELECT * FROM tblData ORDER BY tblData.txtName;"
Set dbs = CurrentDb()
Set rst = dbs.OpenRecordset(strSelect, dbOpenDynaset)
rst.MoveFirst
Me.txtName = rst!txtName
Private Sub btnClose_Click()
'Me.Undo
MsgBox " "
DoCmd.Close acForm, "frmdata", acSaveNo
I would like to form to just close without displaying another record and without overwriting another record in the table.
It is quite possible that your Form has it's DataSource property set to 'tblData'.
So after you Form loads, the Form_Load() event fires, and you modify the first Record of the Table that is set in the Form's DataSource property.
This is the line that modify's the Form data: Me.txtName = rst!txtName

Setting the values of a combo box dynamically on an Access form

I'm trying to dynamically set the value of one combo boxbased on the selection of another. Every time I run this is says object variable or with block variable not set
Option Compare Database
Private Sub cmbReport_AfterUpdate()
'Gets the Report
If cmbReport = "Audit type" Then
Set Data = CurrentDb.CreateQueryDef("", "SELECT AuditTypeName FROM tblAuditType")
End If
Set rs = Data.OpenRecordset
'Sets the data
With Me.cmbData
.Recordset = rs
End With
End Sub
If cmdData is a combo box, it should be .Rowsource not .Recordset
Private Sub cmbReport_AfterUpdate()
If cmbReport = "Audit type" Then
cmbData.Rowsource = "SELECT AuditTypeName FROM tblAuditType"
End If
End Sub