saving a record after deletion - ms-access

I have a form to add a record for my users. The database will automatically add an ID to the record, after it's added with the user clicking a button on the form.
I also have a user activity log. I want to record the record's automatically generated ID number when the form adds a record. How do I access that number from the onClick event of the form?
Private Sub btnAddTax_Click()
Dim SQL As String
SQL = "INSERT INTO tblMain ( field1, field2,... )" _
& "SELECT Forms![field1Box], Forms![field2Box],...;"
DoCmd.RunSQL SQL
MsgBox "Tax Added to the Database"
DoCmd.OpenForm "frmMainScreen"
DoCmd.Close acForm, Me.Name
Dim tempString As String
tempString = "Added a record"
Logging (tempString)
End Sub

Consider code in button click event:
DoCmd.RunCommand acCmdSaveRecord
Debug.Print Me!ID 'or do something else with ID

Related

Jumping to a specific record in a parent form (MS-Access form / VBA)

I have an Access form Form1 with a button that opens Form2. Form2 is not a subform. Form2 has a number of text controls that are unbounded. There is a button called Commit.
When it is clicked, it takes the values in the unbounded controls and inserts them into various tables. One of these is inserted into the source table as Member_Id.
Once the values are inserted, the following is supposed to happen:
Focus is set on Form1.
The Form1 Current record is set to the Member_Id that was inserted into its data source table.
Form2 closes leaving Form1 with the focus displaying the Member_Id record previously inserted.
I am able to do the record insertion, but I can't close Form2. Would anyone have an idea of what I need to do?
Sub Commit_Record_and_Close()
Dim strCriteria As String
Dim rst As DAO.Recordset
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' Insert values including Member_Id into source table HERE.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Forms("Form1").SetFocus
Set rst = Forms("Form1").RecordsetClone
strCriteria = "[Member_Id] = " & CStr(lng_Member_Id) 'ember_Id previously set.
rst.FindFirst strCriteria
Forms("Form1").Bookmark = rst.Bookmark
Forms("Form1").Requery
Forms("Form1").Controls("cbo_Selector").Requery 'drop down that contains Member_Id
' The following 2 lines were inserted in desparation because I couldn't get Form1 to requery.
DoCmd.OpenForm "Form1", acDesign
DoCmd.OpenForm "Form1", acNormal, , strCriteria
Me.SetFocus ' Form2
DoCmd.Close acForm, Me.Caption, acSavePrompt ' Form2
End Sub
To make the search/goto record work, you need to first requery the form and control, then search and goto. Otherwise the search can't find the new record.
Forms("Form1").Requery
Forms("Form1").Controls("cbo_Selector").Requery 'drop down that contains Member_Id
Set rst = Forms("Form1").RecordsetClone
strCriteria = "[Member_Id] = " & CStr(lng_Member_Id) 'ember_Id previously set.
rst.FindFirst strCriteria
Forms("Form1").Bookmark = rst.Bookmark
To make the Close work, you need the form name instead of its caption.
DoCmd.Close acForm, Me.Name, acSavePrompt ' Form2
If the order of events is
Form1 opens Form2
Form2 closes itself
then you don't need any .SetFocus. Form1 will automatically get the focus back when Form2 closes.

MS Access Combobox not taking a value after requery shows value

I have Combobox that lets users either edit the related values for this field
- cboBEA using a button. I decided to use a NotInList routine whenever they want to ADD a new value. The edit part works without a hitch, but the NotInList part needs to accept a value after providing related fields in a popup form called frmBEA_JDIR
At first the requery of cboBEA wasn't working, so I did a more deliberate resetting of the rowsource by first setting it to "" then the actual SQL of the rowsource.
Here is the code in the "Save" button of the popup form frmBEA_JDR
Private Sub cmdSave_Click()
Select Case Me.OpenArgs
Case "Edit"
DoCmd.Save
DoCmd.Close acForm, "frmBEA_JDIR"
With Form_sfm_AddSPDistro
.cboBEA.Requery
.cboBESA.Requery
.cmbPROGRAM.RowSource = ""
.cmbPROGRAM.RowSource = "SELECT * FROM qLU_BEA_JDIR;"
.cmbPROGRAM = .cboBEA
End With
Case "AddNew"
Dim strSQL As String
strSQL = "SELECT LU_BEA_JDIR.ID, LU_BEA_JDIR.BEA, LU_BEA_JDIR.BESA, LU_BEA_JDIR.ORGANIZATION " _
& "FROM LU_BEA_JDIR;"
With Form_sfm_AddSPDistro
'cboBEA.Requery doesn't work, so...
.cboBEA.RowSource = ""
.cboBEA.RowSource = strSQL
.cboBESA.Requery
.cboBEA.Value = Me.txtBEA
.cmbPROGRAM.RowSource = ""
.cmbPROGRAM.RowSource = "SELECT * FROM qLU_BEA_JDIR;"
.cmbPROGRAM = .cboBEA
End With
DoCmd.Close acForm, "frmBEA_JDIR"
End Select
End Sub
Here is the NotInList event of the calling form:
Private Sub cboBEA_NotInList(NewData As String, Response As Integer)
Dim MsgBoxAnswer As Variant
Response = acDataErrContinue
Me!cboBEA.Undo 'Used this to prevent the requery error caused by frmBEA_JDIR
MsgBoxAnswer = MsgBox(NewData & " is not in the list. Do you want to add it?", vbQuestion + vbYesNo, "Add " & NewData & "?")
If MsgBoxAnswer = vbNo Then
Me.cboBEA = Null
DoCmd.GoToControl "cboBEA"
Else
DoCmd.OpenForm "frmBEA_JDIR", acNormal, , , acFormAdd, , "AddNew"
Form_frmBEA_JDIR.txtBEA = NewData
End If
End Sub
So depending on what calls this form - the NotInList or the Edit, I put it in the openargs parameter that calls frmBEA_JDIR. This is how I handle the update in the SAVE button. Again, the edit part works perfectly, but the AddNew from the NotInList event just won't populate cboBEA even after it is requeried and I can see the new value in it.
In brief: Instead of figuring out what to do in the popup with openargs, let acFormAdd do it for you; acFormAdd will open the form to a new record.
Send the new data in openargs.
Open frmBEA_JDIR in dialog mode. It stops the current code until the opened form is closed.
' open frmBEA_JDIR in dialog mode to add the new data.
DoCmd.OpenForm "frmBEA_JDIR", acNormal, , , acFormAdd, acDialog, "NewData"
'data is added, now requery the dropdown
cboBEA.Requery
Fool around with this without the 'case edit' section until you see it working. Then add the edit part using acFormEdit. You can check the datamode of the popped-up form to see if it's add or edit.

Auto Populate Access Form using simple VBA code by setting a variable

I was recently given the task of creating a form that will autofill with the information from a table. The information the form autofills is selected using a primary key called ModID. I have a combo box that has a List of the ModIDs that are listed as Active.
SELECT ModID
FROM P_Review
WHERE Status = "Active"
Simple enough. I then have VBA code running on the event After Update. So after the value for the combo box is select or changed it will run this VBA code.
Option Compare Database
Option Explicit
Private Sub selectModID_AfterUpdate()
'Find the record that matches the control.
On Error GoTo ProcError
Dim rs As Object
Set rs = Me.RecordsetClone
With rs
.FindFirst "ModID=" & Me.selectModID
If Not .NoMatch Then
Me.Bookmark = .Bookmark
Else
DoCmd.RunCommand acCmdRecordsGoToNew
Me!localModID = Me.selectModID.Column(0)
End If
End With
ExitProc:
Exit Sub
ProcError:
MsgBox "Error: " & Err.Number & ". " & Err.Description
Resume ExitProc
End Sub
The code runs fine (I get no errors when I debug or run).
Now for the access text box. I would like to populate certain fields based off the variable localModID. I have a dlookup in a text box to find the information in the table P_Review.
=DLookUp("Threshold","P_Review","ModID =" & [localModID])
So the DlookUp should find the value for the column threshold, in the table P_Review, where the ModID in P_Review equals the localModID set in the VBA code. But when I go to form view and select a ModID I get the Error 3070: The Microsoft Access database engine does not recognize as a valid field name or expression. I did copy this code from another database we are already using but it fails in this new instance.
Private Sub ModID_AfterUpdate()
Dim rs As Object
Set rs = Me.RecordsetClone
With rs
.FindFirst "ModID='" & Me.ModID & "'"
If Not .NoMatch Then
Me.Bookmark = .Bookmark
Else
DoCmd.GoToRecord , , acNewRec
Me!ModID = Me.ModID
End If
End With
End Sub
This is the answer to question. I used this code to auto update.
Try
Forms!<whatever_this_form_name_is>![localModID]
in your DLOOKUP

Setting a value of a field in my table for future use

I have an access Db which was originally written ib Access 2003 but has since been upgraded to Access 2007 - the problem I am experiencing is as follows:
I have a table "tblBookings" which stores all relevant data for a particular clienst booking or quote, the client field of this table is linked to the PK of the CLient Table (tblClients) when a quote is accepted the user opens the main form, selects the client and in a dropdown selects the booking number then proceeds to "Edit booking" where the user can either edit the booking or confirm it. when the user clicks "confirm Booking" cmdButton the open form closes and the "Create Invoice" form opens. From a dropdown list the user selects the booking number and then prints the Pro-Forma Invoice or invoice. the print pro-forma cammand button opens a report that prints the necessary document, when the Print Invoice command is clicked then the print invoice form is opend where the user has the option to record any ayments made against the invoice.
This being said it is essential to first print a pro-forma before printing an invoice so i need to set a yes no field in the table to yes or true if a pro forma has been printed in which case the invoice button will become visible and remain hidden if one has not been printed yet.
the event procedure on cmdProForma is below (this is where I need ti set the yes/no field in the Pro field which is tblBookings and set to a yes/no field.
Private Sub CmdProForma_Click()
Dim rs As New ADODB.Recordset 'recordset of existing refs
Dim t As String 'temp string var
Dim stDocName As String
Dim stLinkCriteria As String
Dim i As Integer 'temp ref variable
i = CInt(Right(txtBRef, 5))
t = [txtBRef]
With rs
.Open "SELECT BRef,Conf,lock,Pro FROM tblBookings WHERE Bref=" & t & ";", CurrentProject.Connection, adOpenDynamic
If .BOF Or .EOF Then 'no such ref
MsgBox "No booking with ref '" & fRef(CInt(t), "B") & "' exists.", vbExclamation, "No booking"
Else 'ref found: open invoice
strSQL = "UPDATE tblBookings SET Pro = True"
'db.Execute strSQL, dbFailOnError
DoCmd.Close acForm, "frmBRefEnter"
' !Form!frmBRefEnter!Pro = True
DoCmd.OpenReport "rptInvoice1", acViewPreview, , "BRef=" & t
DoCmd.OutputTo acOutputReport, "rptInvoice1", acFormatPDF, destDIR & "\Inv\" & fRef(i, "Pro-Forma") & ".pdf"
End If
End With
End Sub
Add the checkbox for proforma printed to the form. It will be a good guide for your users as to why they cannot print an invoice. You can set the properties to Locked=True
Private Sub CmdProForma_Click()
''"From a dropdown list the user selects the booking number",
''so the booking number must exist, no need to check
DoCmd.OpenReport "rptInvoice1", acViewPreview, , "BRef=" & Me.txtBref
DoCmd.OutputTo acOutputReport, "rptInvoice1", _
acFormatPDF, destDIR & "\Inv\" & fRef(i, "Pro-Forma") & ".pdf"
Me.Pro = True ''Checkbox
DoCmd.Close acForm, "frmBRefEnter"
End Sub
For the invoice button:
Me.cmdInvoicePrint.Visible = Me.Pro
If Me.Pro is ticked, Me.Pro will be true and the invoice button will be visible.

MS Access form to edit specific record from a form by providing input through text box

Can someone please help me on this find specific record Edit through MS access Forms
I have Frmfind form where I have one filed "ticket#" is a input text box
another filed was button "find"
When I enter ticket# which is primary key for my table. I need get the the specific ticket# record should be opened in FormEdit mode using VBA code...
So I have another form "frmEdit" of specific record which has to be called from frmfind -> specific input..
note: Ticket# is column in my table whcih it is primary to have the ticket#.
Code:
Option Compare Database
Private Sub find_Click()
If IsNull(Me.Text79) Or Me.Text79 = "" Then
MsgBox "You must enter a Ticket #", vbOKOnly, "Required Data"
Me.Text79.SetFocus
Exit Sub
End If
If [Ticket#] = Me.Text79.Value Then
MsgBox "Record found"
DoCmd.Close
DoCmd.OpenForm "frmEdit"
Else
MsgBox "not matching record"
Me.Text79.SetFocus
End If
End Sub
Private Sub Form_Open(cancel As Integer)
'On open set focus to text box
Me.Text79.SetFocus
End Sub
You can use this code:
Private Sub Command112_Click()
Me.txtSeach.SetFocus
On Error Resume Next
DoCmd.OpenForm "frmEdit", , , "TicketNumber = '" & Nz(Me.text79, "") & "'"
End Sub
Note in above if TicketNumber is in fact a number column and not text, then remove the single quotes and use this:
DoCmd.OpenForm "aa", , , "TicketNumber = " & Nz(Me.text79, "")
Then for your message, just place that code in the forms on-open event that has a cancel:
eg:
Private Sub Form_Open(Cancel As Integer)
If IsNull(Me!TicketNumberID) Then
MsgBox "Please enter a valid Ticket #", vbOKOnly, "Required Data"
Cancel = True
End If
End Sub
The above assumes your search column is ticket number.
You can also use dlookup(), or even dcount(). I think above is less code, but:
Dim strWhere As String
strWhere = "TicketNumber = " & Me.text79
If DCount("*", "tblBookings", strWhere) > 0 Then
code for Record found goes here
Else
code reocrd not found code here
End If
So either way should suffice here.