Changing existing record when saving new record - ms-access

Problem: I have records that act like information snapshots, and I need to be able to change a yes/no field from False to True on the current existing record when I save a new record.
For arguments sake, records X and Y are the same subject, just at different point in time (same document, different revisions). I need to save a new record, record Z, which is the same subject with today's updates. When I save record Z, I want record Y to have a checkbox modified from False to True to show it is obsolete.
When saving a new record, I do have an unbound text box that displays the existing record number (named txtID). Is there a way I can piggyback a reference to that box in order to change a check box control (named chkObs) on that record?
My current coding to save a record is as follows:
Private Sub cmdSave_Click()
DoCmd.OpenTable "tblTasks", acViewNormal
DoCmd.Requery
Dim db As Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("Tasks")
rs.AddNew
rs("Namefield").Value = Me.NameD.Value
rs("Reqt").Value = Me.ReqT.Value
rs("Plant").Value = Me.Plant.Value
rs("Requestor").Value = Me.Requestor2.Value + " " + Me.Requestor.Value
rs("TaskDue").Value = Me.TDD.Value
rs("AssignedERDM").Value = Me.AE.Value
rs("Package").Value = Me.SUBN.Value
rs("Comments").Value = Me.COM.Value
rs("RequestRec").Value = Me.DRR.Value
rs("Hold").Value = Me.H.Value
rs("QuantityT").Value = Me.QT.Value
rs("QuantityC").Value = Me.QC.Value
rs("QuantityO").Value = Me.QR.Value
rs("ERDMLogged").Value = Me.ELT.Value
rs("Closed").Value = Me.Cl.Value
rs("Hyperlink").Value = Me.hy.Value
rs("DateMod").Value = Me.lm.Value
rs("StatusAW").Value = Me.SSO.Value
rs("CompleteDate").Value = Me.CD.Value
rs.Update
DoCmd.Close acTable, "tblTasks", acSaveYes
DoCmd.Requery
End Sub

Related

MS Access 2013 saved append query not updating all fields

I have a saved query, qryInsertLog which is as follows:
PARAMETERS UserIDPar Long, UnitIDPar Long, LogEntryPar LongText, FNotesPar LongText;
INSERT INTO tblLogBook ( UserID, UnitID, LogEntry, FNotes )
SELECT [UserIDPar] AS Expr1, [UnitIDPar] AS Expr2, [LogEntryPar] AS Expr3, [FNotesPar] AS Expr4;
I'm trying to run this query when a save button is clicked on an unbound form, where the parameters are gathered from the form controls. My VBA code for the save button is:
Private Sub cmdSave_Click()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim okToSave As Boolean
If Me.cboUser.Value = 0 Or IsNull(Me.cboUser.Value) Then
MsgBox "You must choose a user. Record not saved."
okToSave = False
ElseIf Me.cboUnit.Value = 0 Or IsNull(Me.cboUnit.Value) Then
MsgBox "You must choose a unit. Record not saved."
okToSave = False
ElseIf Me.txtLogEntry.Value = "" Or IsNull(Me.txtLogEntry.Value) Then
MsgBox "You must have somtehing to log. Record not saved."
okToSave = False
Else
okToSave = True
End If
Set db = CurrentDb
Set qdf = db.QueryDefs("qryInsertLog")
qdf.Parameters("UserIDPar").Value = Me.cboUser.Value
qdf.Parameters("UnitIDPar").Value = Me.cboUnit.Value
qdf.Parameters("LogEntryPar").Value = Me.txtLogEntry.Value
qdf.Parameters("FNotesPar").Value = IIf(IsNull(Me.txtFNotes.Value), "", Me.txtFNotes.Value)
If okToSave Then
qdf.Execute
End If
qdf.Close
Set qdf = Nothing
End Sub
When this code is run, the FNotes field of the table isn't updated. The other three fields update as expected. FNotes is the only field which isn't required. I hardcoded a string for FNotes paramater like so:
qdf.Parameters("FNotesPar").Value = "why doesn't this work"
rather than using the form control value, and got the same result: that field just doesn't update. When I run this query from the Access Objects window and supply parameter values from the prompts, it works just fine. When I create form that's bound to the table, it also seems to work just fine.
I can't figure out why there's no trouble updating the LogEntry field but the FNotes field fails to update.
Add the new record via a DAO.Recordset instead of a DAO.QueryDef.
First, include this declaration ...
Dim rs As DAO.Recordset
Then use this after Set db = CurrentDb ....
Set rs = db.OpenRecordset("tblLogBook")
With rs
If okToSave Then
.AddNew
!UserID = Me.cboUser.Value
!UnitID = Me.cboUnit.Value
!LogEntry = Me.txtLogEntry.Value
!FNotes = Nz(Me.txtFNotes.Value, "")
.Update
End If
.Close
End With
Note Nz(Me.txtFNotes.Value, "") gives you the same thing as IIf(IsNull(Me.txtFNotes.Value), "", Me.txtFNotes.Value), but more concisely.

Access VB: Validating blank values and incorrect values in a textbox

I have a textbox where the user inputs the ID of a row to be updated/edited. I got it to work properly when they enter an ID that exists, but I get an error when they input an ID that doesn't exist or when they leave it blank.
Goals:
Allow blank - if the user leaves the field blank, then I need to wipe the form and simply let the user continue (no message box needed).
Warn user when ID is not valid with a message box.
Current Code
Private Sub Text135_LostFocus()
If Me.Text135 = Nothing Then
MsgBox "Nothing entered into the ID field. Query will not run"
GoTo Last_Line:
Else
sql = "SELECT * FROM tbl_Downtime WHERE ID = " & Forms![DTForm]![Text135] & ";"
Set db = CurrentDb
Set rs = db.OpenRecordset(sql)
Me.Text126.Value = rs!production_date
Me.Text144.Value = rs!shift
Me.Text116.Value = rs!job
Me.Text118.Value = rs!suffix
Me.Text121.Value = rs!reason
Me.Text123.Value = rs!downtime_minutes
Me.Text4.Value = rs!people_missing
Me.Text128.Value = rs!comment
Set db = Nothing
Set rs = Nothing
Last_Line:
End If
End Sub
Completely stop executing the sub when the field is blank:
If Nz(Me.Text135) = "" Then 'Text135 is null or empty
Exit Sub
End If
But if the code in your question is your actual code (and not just a shortened example), you need neither the Exit Sub nor the GoTo Last_Line: part, because after the message box, the code execution will jump to the End If anyway.
Check whether the Recordset contains any rows:
Set db = CurrentDb
Set rs = db.OpenRecordset(sql)
If rs.EOF Then
'rs.EOF is True when there are no rows
MsgBox "ID is not valid"
Else
'do stuff
End If
Set db = Nothing
Set rs = Nothing

vba access run time error 3265

I am new to programming in VBA. I am trying to copy Form data from an existing form when I click on the Copy Record button. This is supposed to copy the current form data as a new record with a new master_id (that is autonumbered) and have Brand as blank field for them to fill in. I get a:
Run Time Error 3265 "Item not found in this collection"
at the new_master_id that i created. I am not sure how to fix this problem. Any help is appreciated.
Private Sub Copy_Record_Click()
Dim RS As DAO.Recordset, C As Control
Dim FillFields As String, FillAllFields As Integer
Dim New_MASTER_ID As Integer
New_MASTER_ID = (DMax("[MASTER_ID]", "tbl_Drug_Master") + 1)
Dim BRAND As String
BRAND = ""
Set RS = CurrentDb.OpenRecordset(Name:="tbl_Drug_Master", Type:=RecordsetTypeEnum.dbOpenDynaset)
With RS
.AddNew
![MASTER_ID] = ![New_MASTER_ID] <--this is where the problem is...
![MASTER_KEY] = Me![MASTER_KEY]
![PRODUCT_CATEGORY] = Me![PRODUCT_CATEGORY]
![BRAND] = Me![BRAND]
![GENERIC] = Me![GENERIC]
![STUDY_NAME] = Me![STUDY_NAME]
![MANUFACTURER] = Me![MANUFACTURER]
![MASTER_COMMENTS] = Me![MASTER_COMMENTS]
.Update
End With
End Sub
ok so firstly, im not sure why the following are required:
dim c as control
Dim FillFields As String, FillAllFields As Integer
New_MASTER_ID = (DMax("[MASTER_ID]", "tbl_Drug_Master") + 1)
Dim BRAND As String
BRAND = ""
therefore I am leaving them out as part of this question because they appear unnecessary. Brand is not required because you are creating a new record and putting nothing in the brand field so it will remain blank.
I am also not too sure why you have 2 tables both that are the same? I think what should happen is that you simply copy the data to a new record in the same table.
You will see I have put a save record command in to the routine. other additions such as error handling is also recommended.
Private Sub Copy_Record_Click()
docmd.runcommand accmdsaverecord
Dim RS As Recordset
Set RS = CurrentDb.OpenRecordset(Name:="tbl_Drug_Master", Type:=RecordsetTypeEnum.dbOpenDynaset)
With RS
.AddNew
![MASTER_KEY] = Me.MASTER_KEY.value
![PRODUCT_CATEGORY] = Me.PRODUCT_CATEGORY.value
![GENERIC] = Me.GENERIC.value
![STUDY_NAME] = Me.STUDY_NAME.value
![MANUFACTURER] = Me.MANUFACTURER.value
![MASTER_COMMENTS] = Me.MASTER_COMMENTS.value
.Update
End With
Set RS = Nothing
End Sub
I was mistaken with my comment rs.close it would be db.close but you are using the currentdb and no reason to close it. This procedure will remain on the original record, if you want to go to the new record you will have to add a command like docmd.gotorecord acdataform, , aclast before the end of the routine.

VBA code works in Access97 but not 2010

The 1st record in the open order table matches a record in the Bookings table but the NO MATCH = True is happening and therefore it goes down thru the code anf tries to insert a new record. This is true for several records in the file and it tries to add the record even though there is a match. If I set the NO MATCH = False then it does the else. I imported these table from Access 97 to 2010 where it is working correctly. Any help would be appreciated.
Additional note: While in Debug, If I hover the mouse over the .Seek "=", TempCust, TempPart fields, it shows the 1st record in the table and that data is in the Bookings table. Not understanding why it is not matching?
Sub Get_Current_Info()
DoCmd.SetWarnings False
Dim rstOpenOrd, rstBookings As Recordset
Dim TempCust, TempPart, TempQty, TempDollars As Variant
Set rstOpenOrd = CurrentDb.OpenRecordset("Open Orders", dbOpenTable)
Set rstBookings = CurrentDb.OpenRecordset("Bookings", dbOpenTable)
'Get the open orders
Do While Not rstOpenOrd.EOF
With rstOpenOrd
TempCust = !ODCSNO
TempPart = !ODITNO
TempQty = !ODQTOR
TempDollars = !OrdDollars
End With
With rstBookings
.Index = "PrimaryKey"
.Seek "=", TempCust, TempPart
If rstBookings.NoMatch = True Then
With rstBookings
.AddNew
!cusno = TempCust
!PrdNo = TempPart
!Qty_booked = TempQty
!Dol_booked = TempDollars
!Yest_qty_booked = 0
!Yest_dol_booked = 0
!Shipped_qty = 0
!Shipped_dol = 0
.Update
End With
Else
With rstBookings
.Edit
!Qty_booked = !Qty_booked + TempQty
!Dol_booked = !Dol_booked + TempDollars
.Update
End With
End If
End With
rstOpenOrd.MoveNext
Loop
End Sub
This line suppresses information, including many types of error information ...
DoCmd.SetWarnings False
I don't see why you would want it at all in this procedure. But, at least during troubleshooting, make sure SetWarnings is on ...
'DoCmd.SetWarnings False
DoCmd.SetWarnings True
The point is that you need every possible tidbit of information you can get while troubleshooting. Don't suppress any of it.
The code would not do what you expect if the Bookings table does not include an index named PrimaryKey, or if that index does not include cusno and PrdNo (in that order) as its first 2 keys.
But that is just speculation. You need to test with SetWarnings on and see whether Access gives you useful details.
You must dim your variables or they are just Variant/Object:
Dim rstOpenOrd As DAO.Recordset
Dim rstBookings As DAO.Recordset

Cannot Update. Database or Object is Read-only after Requery

Okay, cannot find anything online about this error, so here goes.
Using Access 2003. I have a form that has a combobox dropdown. Users choose from the dropdown, and the VBA code looks at a particular table to see if data already exists. If it finds it, it displays the data associated with the record. If it does not find it, it adds a new record to the table, then tries to display the new data. The problem is that when using the following code, it does not display the new data, unless I add in Me.Requery. However, if I do that, it then gives me the above error if I try to do the same process again.
So, how can I get the data to display after adding without the above error?
Here is the relevant code...
' Find the record that matches the control.
Dim rs As DAO.Recordset
Set rs = Me.Recordset.Clone
'if no record found, then add a default record
If IsNull(Combo119) Then
Set rs = CurrentDb.OpenRecordset("SELECT * FROM [Master Reject Data]")
rs.AddNew
rs.Fields("production Date") = Date
rs.Fields("Work Order #") = Combo119.Column(0)
rs.Fields("Product Type") = ""
rs.Fields("Shift") = ""
rs.Fields("Line") = ""
rs.Fields("# Produced") = 0
rs.Fields("Reject Type") = ""
rs.Fields("Reject Quantity") = 0
rs.Fields("Reject Category") = "Rejection"
Dim tRec As Long
tRec = Combo142.ItemData(0)
rs.Fields("Report Number") = tRec
rs.Update
Me.Requery 'this is the line I added to try to get the data to appear
Set rs = Me.Recordset.Clone
rs.FindFirst "[Report Number] = " & tRec 'navigate to the newly added record
Else
rs.FindFirst "[Report Number] = " & Nz(Me![Combo119], 0) 'navigate to the record with the requested report number
End If
If Not rs.EOF Then Me.Bookmark = rs.Bookmark
Sorry, found the issue after looking at it again. The problem is that the Me.Requery statement needs to be Me.Recordset.Requery. After doing that and adding Me.Refresh, it works as intended.
To avoid requerying I think you should open the recordset specifying that it should be a dynaset
CurrentDb.OpenRecordset("SELECT * FROM [Master Reject Data]", dbOpenDynaset) - in case you want to make it a bit neater. as for the small bug, I see you've already found yourself