If an Access table has a new record selected, It displays (New). How do I get my code to recognize the (New) value? - vba

I Want to be able to let the end user of the database know when they are on a new record, but I do not want to display the actual id's. I just want the text box to display "New" when it is a new record.
I have two buttons one the selects the previous record and the other that selects the next record. The next record button has the code that I am trying to get to work.
Private Sub Command25_Click()
On Error GoTo Command25_Click_Err
On Error Resume Next
DoCmd.GoToRecord , "", acNext
' I wrote this if statment to capture the (New)
If frmQuote_QuoteID.Value = " " Then
frmQuote_QuoteNumber.Value = "NEW"
End If
If (MacroError <> 0) Then
Beep
MsgBox MacroError.Description, vbOKOnly, ""
End If
Command25_Click_Exit:
Exit Sub
Command25_Click_Err:
MsgBox Error$
Resume Command25_Click_Exit
End Sub
I have also tried if frmQuote_QuoteID.value = "(New)" Then
I am trying to get this to the point where the form can display New based on an empty primary key field, but if it is not a new record then I don't want anything displayed

You need to use
if me.NewRecord then

Related

Creating report for each value in listbox

I have a form, with a listbox. User can choose record and add it to a list box using listbox. I want to create a VBA script to open a report and match all the values in listbox with corresponding records. So far i can do this with single one, but for many i don't know what is going on. Here is the code:
Private Sub btnSearchMany_Click()
Dim i As Long
With Me.List12
If .ListCount = 0 Then
MsgBox "Brak wybranych wpisow.Dodaj wpisy, wybierajac je z listy i wciskajac przycisk dodaj.", vbCritical
Exit Sub
End If
For i = 0 To .ListCount - 1
DoCmd.OpenReport "rptKKsy", acViewReport, , "[tblKKsy].[KKS]='" & .List12(i) & "'"
Next i
End With
End Sub
List12- lisbox that user can add records "later i will rename it"
rptKKsy- my report
tblKKsy- table that stores values
KKs - one of the values stored in my table
I always getting error: method or data member not found. I tried to replace:
With Me.List12
with
With Forms("frmSearch").Form.list12
But it just created another error.
Edit: As suggested, my list box is a value list, and user can put thing in it by using a combobox and clicking a button ( button have addItem command programed). After user add some things, i want to open a report for each value stored in listbox. I dont want user to select things in listbox, because we will be using everything in it so its not nedded. I tried to use Item.Data property as June7 linked to, but ill be honest: I dont get it. Here is the code:
Private Sub btnSearchMany_Click()
Dim i As Long
Dim lValue As String
With Me.List12
For i = 0 To .ListCount - 1
If .ListCount = 0 Then
MsgBox "Brak wybranych wpisow.Dodaj wpisy, wybierajac je z listy i wciskajac przycisk dodaj.", vbCritical
Exit Sub
End If
Next i
End With
If i = Len(lValue) > 2 Then
DoCmd.OpenReport "rptKKsy", acViewReport, , "[tblKKsy].[KKS]='" & .ItemData(lValue) & "'"
End If
End Sub

Subform blocking Recordset.AddNew (Error 3027)

Having a subform displaying the same table used in recordset makes the table read only (error 3027). Getting rid of the subform fixes the problem. Similar setup works in my other form interface.
I tried to delete the subform, which fix the accessibility problem. But that would defeat the original UX purpose.
Option Explicit
Public UnitRS As DAO.Recordset
Public ModelRS As DAO.Recordset
Public NameUnitRecords As String
Public NameModelRecords As String
Public Sub Form_Load()
'Initialization
NameUnitRecords = "tblBatteriesMainRecordsUnits"
NameModelRecords = "tblBatteriesRecordsModels"
End Sub
Private Sub SetUnitRecordsets()
'Set the path to the Battery Records table
Set UnitRS = CurrentDb.OpenRecordset(NameUnitRecords, dbOpenDynaset)
End Sub
Private Sub txtBatteryID_AfterUpdate()
'Set the recordset path for unit records
Call SetUnitRecordsets
'do a findfirst search for the Battery ID, using value from textbox txtBatteryID
UnitRS.FindFirst "[Battery ID]=" & txtBatteryID
'If no matching record, leave the other fields empty
If UnitRS.NoMatch Then
'If there is a matching record, then, grab the model number
Else
'as there is an existing record with model number, run a search on the model number and grab the model info
End If
'close recordset
UnitRS.Close
'check if the button can be enabled
End Sub
Private Sub cmbModelNumber_AfterUpdate()
'Set the recordset path for model records
'do a findfirst search for the Model Number, using value from combobox cmbModelNumber
'If no matching record, leave the other fields empty
If ModelRS.NoMatch Then
'If there is a matching record, then, grab the Model Info
Else
End If
'close recordset
'check if the button can be enabled
End Sub
Private Sub btnSaveAndCLear_Click()
Dim Response, strOldModelNumber
'Set the recordset path for unit records
Call SetUnitRecordsets
'Set the recordset path for model records
'close all related tables, queries and forms
DoCmd.Close acTable, NameUnitRecords, acSaveYes
DoCmd.Close acForm, "frmSubBatteriesMainRecordsUnits", acSaveYes
'If a new model record is required
ModelRS.FindFirst "[Model Number]='" & cmbModelNumber & "'"
If ModelRS.NoMatch Then
'msg box confirm model information
'If user chooses yes
If Response = vbYes Then
'create new model record
'this block could be done with "With...End" format for less error vulerability?
'nah, unless it is repetitively called, it's too much work to inplement just the .addnew part
'requery the two combobox to reflect newest changes
'User chooses no
Else
'popup a message telling the user the battery and model record is not logged, but don't clear the field.
Exit Sub
End If
End If
'need to find the record first, otherwise it will edit the first one
UnitRS.FindFirst "[Battery ID]=" & txtBatteryID
'store the old model number value
strOldModelNumber = UnitRS("Model Number")
'New record
If UnitRS.NoMatch Then
'create a new battery record
UnitRS.AddNew
UnitRS("Battery ID") = Me.txtBatteryID
'If this is an edit on existing record
Else
'if the new value is the same as the old one
If strOldModelNumber = cmbModelNumber Then
'msgbox the same value, no change is done to the database
MsgBox "the data is the same as the old record, no change is made to the record", vbInformation, "Same data"
Exit Sub
Else
'msg box confirm edit
Response = MsgBox("Please confirm edit on existing record: " & Chr(13) & Chr(10) & "BatteryID: " & txtBatteryID & Chr(13) & Chr(10) & "Model Number: " & cmbModelNumber, vbYesNo, "New Model Record Dectected")
'If user chooses yes
If Response = vbYes Then
'goto edit mode
UnitRS.Edit
'if user chooses no
Else
'msgbox notify the user nothing is changed in the database
MsgBox "Battery and Model record not logged, you may retry logging", vbInformation, "Record not logged"
Exit Sub
End If
End If
End If
'both changes the model number and comment field anyway
UnitRS("Model Number") = Me.cmbModelNumber
UnitRS("Comment") = Me.txtComment
'commit update
UnitRS.Update
UnitRS.Close
'clear all flieds
'reset all locks
'requery the sub form to reflect the newest changes
Me.subFrmBatteryRecords.Requery
End Sub
What I would like to achieve is to have a display in the form interface to show the content of the actual record table, so that the user knows what is in the table.
There is nothing wrong with my code. There is a property option in the form object, it's called "record lock", somehow mine had "All Records" selected. By making it "No locks", the accessibility problem is gone.

MS Access '16 - Query not pulling a value from a field

[Disclaimer: I'm self-taught and a total novice!]
I have a FORM with which a QUERY pulls data and uses it to populate a REPORT. As the end user finishes the report and clicks a button, the following is supposed to happen:
1) The FORM saves all the data in a new record on the TABLE 2) A query pulls that record by the ID (which is autonumbered) from the FORM 3) The QUERY populates a REPORT with the data from the TABLE 4) The FORM and QUERY close - no need to save.
The QUERY pulls all the data from the corresponding TABLE with the following criteria: [Forms]![Data_Input_Form]![ID]
However, my REPORT comes up blank! Eek!
I have a similar QUERY that pulls data from the same TABLE and populates it to a similar REPORT with the following criteria: Like Nz([Forms]![Home_Form]![Incident_ID_Lookup_text],"*")
Unsurprisingly, when I added this to the QUERY that wasn't working how I wanted it to, it reported ALL the previous records.
'------------------------------------------------------------
' Add Report [and Open Report] Button Click
'
'
'------------------------------------------------------------
Private Sub Add_Rpt_Btn_Click()
If MsgBox("Are you sure? No backsies.", vbYesNo, "Add Report?") = vbNo Then
Exit Sub
End If
'Check for Necessary Fields and Add New Record
If (IsNull(Me.Person_Filing) Or IsNull(Me.Nature_Lst) Or IsNull(Me.Location_Cmb) Or IsNull(Me.Summary) Or IsNull(Me.Narrative)) = True Then
MsgBox "Looks like you left some important information out. Please fill out all fields with an asterisk.", vbOKOnly, Whoops
Exit Sub
Else
DoCmd.GoToRecord , , acNewRec
End If
'Run Query to Open Report
DoCmd.OpenQuery "Form_to_Report_Qry"
DoCmd.OpenReport "Incident_Report_1", acViewReport, , [ID] = [Forms]![Data_Input_Form]![ID]
'Close Query without Saving
DoCmd.Close acQuery, "Form_to_Report_Qry", acSaveNo
'Close Form without Saving
DoCmd.Close acForm, "Data_Input_Form", acSaveNo
End Sub
The REPORT needs to populate with the most recent record, but it keeps coming up blank.
That's because you move a new (empty) record - having no ID.
I guess, all you need is to use the current ID of the form - and use the correct syntax for the filter:
Private Sub Add_Rpt_Btn_Click()
If MsgBox("Are you sure? No backsies.", vbYesNo, "Add Report?") = vbNo Then
Exit Sub
End If
' Check for Necessary Fields and Add New Record
If (IsNull(Me.Person_Filing) Or IsNull(Me.Nature_Lst) Or IsNull(Me.Location_Cmb) Or IsNull(Me.Summary) Or IsNull(Me.Narrative)) = True Then
MsgBox "Looks like you left some important information out. Please fill out all fields with an asterisk.", vbOKOnly, Whoops
Exit Sub
End If
' If not saved, save the current record.
If Me.Dirty = True Then
Me.Dirty = False
End If
DoCmd.OpenReport "Incident_Report_1", acViewReport, , "[ID] = " & Me![ID].Value & ""
' Close Form without Saving
DoCmd.Close acForm, Me.Name, acSaveNo
End Sub

Executing Append Query not doing anything

Executing Append Query not doing anything
I'm having an odd problem that just reared its ugly head for some reason. I have a form that is used to add/edit/delete records in tblWorkOrder. When the record is saved, a check is made to see if the companion record in tblServiceRecord exists, and if not (like if it were the first time the record in tblWorkOrder is being saved/input) it will execute a query (qryCreateSR).
Several weeks ago it worked just fine. I had no problems with it, but then I updated tblServiceRecord to add several new columns and now it's not working at all. However, the SQL for the query doesn't delineate any of these new columns, let alone any specific information from tblWorkOrder. So I'm not entirely sure how this bug came up.
Here is the SQL:
INSERT INTO tblServiceRecord ( WorkOrderID )
SELECT Forms![frmWorkOrders].Form![txtID];
And here is the code behind the command button:
Private Sub cmdSave_Click()
If DCount("*", "[tblServiceRecord]", "[WorkOrderID] = " & [Forms]![frmWorkOrders].[Form]![txtID]) > 0 Then
Else
DoCmd.SetWarnings False
DoCmd.OpenQuery "qryCreateSR"
End If
DoCmd.RunCommand acCmdSaveRecord
DoCmd.GoToRecord , "", acNewRec
Me.lstWorkOrders.Requery
Me.lstWorkOrders.Value = ""
Me.txtComments.Value = ""
cmdSave_Click_Exit:
Exit Sub
cmdSave_Click_Err:
MsgBox Error$
Resume cmdSave_Click_Exit
End Sub
After removing the warnings suppression I get a key violation issue.
No clue what is causing the key violations. I checked my tables, and the two tables in question are tblWorkOrder and tblServiceRecord. Both have no records in them, I compacted the database, the linked fields (in tblServiceRecord, there is a reference to tblWorkOrder with the field WorkOrderID) are set to the same data type (number), and the child-tables are set to Indexed (No).
Just in case anyone wants to look at the database itself, here is a link:
https://drive.google.com/open?id=1_T-G9fyYQYjH3-YBe4PXhbBDTKNmY3ce
Try saving the current record in the form (by setting Me.Dirty = False), before inserting the record to the other table. Since you try to insert into a child table with a relation to a parent table, you must have a corresponding (saved) record in the parent table. When you create a new entry in the form, it first doesn't exist in the table until it is saved for the first time.
Private Sub cmdSave_Click()
Me.Dirty = False ' Or DoCmd.RunCommand acCmdSaveRecord <==== Save here
If DCount("*", "[tblServiceRecord]", "[WorkOrderID] = " & [Forms]![frmWorkOrders].[Form]![txtID]) = 0 Then
DoCmd.SetWarnings False
DoCmd.OpenQuery "qryCreateSR"
End If
'Removed: DoCmd.RunCommand acCmdSaveRecord <==== instead of here
DoCmd.GoToRecord , "", acNewRec
Me.lstWorkOrders.Requery
Me.lstWorkOrders.Value = ""
Me.txtComments.Value = ""
cmdSave_Click_Exit:
DoCmd.SetWarnings True
Exit Sub
cmdSave_Click_Err: // This code will never run, since a "On Error Goto cmdSave_Click_Err" is missing
MsgBox Error$
Resume cmdSave_Click_Exit
End Sub

access vba Reopen a record using combo box

Hi I am working on patient management tool where in i wanted to have patient engagement status fields as open,close and reopen. when i change the closed patient to reopen it should add it as new record instead of updating the current record. I have tried to do it in the "cmdsave" to check for status and then add as new or update.
the issue is whenever i changed the combo box, the value is getting saved in the table even before i clicked the save command.
Private Sub CmdSaveEng_Click()
On Error GoTo CmdSaveEng_Click_Err
On Error Resume Next
Call checkReopenexists
If pExists = False Then
saved = True
Call addNewRecord
Me.CmdSaveEng.Enabled = False
saved = False
Exit Sub
Else
saved = True
DoCmd.RunCommand acCmdSaveRecord
Me.CmdSaveEng.Enabled = False
saved = False
If (MacroError <> 0) Then
Beep
MsgBox MacroError.Description, vbOKOnly, ""
End If
Beep
MsgBox "Data Saved Successfully", vbInformation, "Save"
End If
CmdSaveEng_Click_Exit:
Exit Sub
CmdSaveEng_Click_Err:
MsgBox Error$
Resume CmdSaveEng_Click_Exit
End Sub
You can't do it that way.
Create a button that will create a copy of the current record, then move to the copied record for further editing:
Copy record to new record