How to stop records from being overwritten on close - vba

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

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

Form event procedure not moving to last record

I am experiencing some odd behavior from a form I am creating in an access database. I have a form called frmSeedling with a subform called frmSeedling detail. frmSeedling gets launched by an event procedure from a command button on a separate form called frmTransect. The OpenArgs passes the primary key of frmTransect called Transect_OID to frmSeedling. Transect_OID is the link field between frmSeedling and frmSeedlingDetail. I have a Form_Current event procedure in frmSeedling to count the number of unique entries on frmSeedling, and create a custom unique id called Seedling_OID. The tables that are the record source for these forms are linked ODBC tables. Below is the code:
Private Sub Form_Current()
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
If Not (rs.EOF) Then
rs.MoveLast
End If
Set rs = Nothing
If IsNull(Seedling_OID) Then
Entry_No = Nz(DCount("Seedling_OID", "rd_Seedling", "Transect_OID = '" & Me.Transect_OID & "'"), 0) + 1
Seedling_OID = Transect_OID & "SD" & Entry_No
End If
End Sub
However, when I launch frmSeedling from frmTransect, I get an error saying I am trying to overwrite the primary key. When I look at the form, this is happening because somehow Access is try to create a new record at the beginning of the form instead of the end of the form, thus thinking that the unique Id I have: created has already been used. Here is a screenshot to show what I mean:
What is curious is that with a separate form called frmDWD with subform frmDWDdetail, I have used this exact setup and it worked fine. Here is the code from frmDWDdetail:
Private Sub Form_Current()
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
If Not (rs.EOF) Then
rs.MoveLast
End If
Set rs = Nothing
If IsNull(DWD_OID) Then
DWD_Piece = Nz(DCount("DWD_OID", "rd_DWD", "Transect_OID = '" & Me.Transect_OID & "'"), 0) + 1
DWD_OID = Transect_OID & "W" & DWD_Piece
End If
End Sub
And here is what that looks like:
Notice how in frmDWD, the record being edited is the last record in the form, while in frmSeedling it is trying to edit the first record in the form. I have set all of the data properties exactly the same in both form and subform, and at least to my eye the code looks identical. Any SQL reasons why I am getting this behavior? Any ideas for fixes? Thanks!!
After hours of playing "Which-of-these-things-is-not-like-the-other" I discovered that the issue was in the property sheet of the subform. I switched "Filter on Empty Master" from "Yes" to "No" and that solved my issue.
You are not using the recordset for anything, so try this reduced code:
Private Sub Form_Current()
Dim Entry_No As Long
If IsNull(Me!Seedling_OID.Value) Then
Entry_No = Nz(DCount("*", "rd_Seedling", "Transect_OID = '" & Me!Transect_OID.Value & "'"), 0) + 1
Me!Seedling_OID.Value = Me!Transect_OID.Value & "SD" & Entry_No
End If
End Sub

How to load a multiline recordset into an Access form with VBA

I'm runing a query (which is returning the correct data) but how can I loop the recordset and add each line in the form with VBA? Because it's currently adding the last line repeatedly.
Private Sub buscarReservasFio()
Dim strSQL As String
strSQL = "SELECT * FROM tblReservasFio WHERE fk_solicitacao = " & "'" & arrParameters(0) & "'"
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset, dbSeeChanges)
If rs.BOF Or rs.EOF Then
'to-do insert
MsgBox ("Insert")
Else
Do Until rs.EOF
DoCmd.GoToRecord , , acNewRec
Me.ds_funcao = rs.Fields("ds_funcao").Value
Me.fk_titulo = rs.Fields("fk_titulo").Value
Me.nr_cor = rs.Fields("nr_cor").Value
Me.nr_peso = rs.Fields("nr_peso").Value
Me.dt_liberacao = rs.Fields("dt_liberacao").Value
Me.dt_baixa = rs.Fields("dt_baixa").Value
rs.MoveNext
Loop
End If
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
End Sub
Apparently, form is bound to table but your code is populating UNBOUND controls. That's the only way I can replicate your output - which should be expected. The reason multiple rows of same data show is because controls (BOUND or UNBOUND) repeat for each record and since there is only one set of controls, the same data shows in UNBOUND controls for all rows - last record from recordset loop. Step debug and watch data change on form. The GoToRecord action is meaningless because no data is input to BOUND controls. The result is same without that line.
In order to display multiple records from table, bind controls to fields. Then, options to modify nr_peso field with new calculated value when form first opens:
run an UPDATE action SQL
open a recordset of form's RecordsetClone and loop through that recordset and change value of nr_peso field - changes in RecordsetClone will immediately reflect in the form
code physically moves to each record on form and modifies field value

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

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]));

Using query yes/no field for checkbox record source?

First of all, you start with a form named LoginF. Once you choose your login ID, and password; and log in it takes data from the table LoginIntoT for the login ID you chose, and creates a query with said data using this code:
On Error Resume Next
DoCmd.DeleteObject acQuery, "IsAdminQ"
On Error GoTo Err_LoginBtn_Click
Dim qdef As DAO.QueryDef
Set qdef = CurrentDb.CreateQueryDef("IsAdminQ", _
"SELECT IsAdmin " & _
"FROM LoginInfoT " & _
"WHERE EmployeeID = " & LoginCmBx.Value)
Exit_LoginBtn_Click:
DoCmd.Close acForm, "LoginF", acSaveNo
DoCmd.OpenForm "MenuF"
Exit Sub
Err_LoginBtn_Click:
MsgBox Err.Description
Resume Exit_LoginBtn_Click
From there in that query after you log in is only 1 column and 1 row; meaning one piece of data. This data is a yes/no field which is either Yes or No depending on who you logged in as.
On the form it opens after you click the login button it has a logout button. The logout button brings you to the previous login form, and deletes the query (IsAdminQ).
What I am trying to do is attach a yes/no button on a form to take that data, and output if it's yes or no on the query.
I've tried putting this in it's control source:
=[IsAdminQ].[IsAdmin]
Though what that does is output it as a filled in square instead of a checkmark or empty. I have triple state set as no.
How would I attach the checkbox to the query so if the data says yes, then it's a check mark and if it says no it is an empty box?
I understand you.
"On the form it opens after you click the login button it has a logout button", we call it frmLogout. You shall do this:
Solution I:
frmLogout.RecordSource = "IsAdminQ"
Then for your checkbox named MyCheckbox, we set it this:
Me.MyCheckbox.ControlSource = "IsAdmin"
You cannot use this:
Me.MyCheckbox.ControlSource = "[IsAdminQ].[IsAdmin]" ' <= here it's impossible.
Solution II:
On the form frmLogout without setting IsAdminQ as .RecordSource,
In a Public Module, insert this:
Function GetLoginStateIsAdmin()
'
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordSet("IsAdminQ")
GetLoginStateIsAdmin = Nz(rst(0), False)
Set rst = Nothing
'
End Function
Then in the private module of any form, as frmLogout:
Private Sub Form_Open(Cancel As Integer)
'
Me.MyCheckbox.Value = GetLoginStateIsAdmin()
'
End Sub
Set it in addition in design mode:
Me.MyCheckbox.TripleState = false
And check also if the query IsAdminQ has been successfully created in the login step. And open it in Access Navigation Pane by double-clicking on it. And see the value of the query.