Add new entries into sql from ms access front end - ms-access

I have two tables which can be represented by this query (I have made this query the Recordsource of the form):
SELECT tblrcmtask.id, tblrcmtask.rcmtask,tblrcmtaskoptions.id,
tblrcmtaskoptions.rcm_id,
tblrcmtaskoptions.rcmtaskoptions
FROM tblrcmtask
INNER JOIN tblrcmtaskoptions
ON tblrcmtask.id=tblrcmtaskoptions.rcm_id
I want the user to be able to add new entries into these table via a form in access 2007.
Columns tblrcmtask.id and tblrcmtaskoptions.id are the primary keys of the tables tblrcmtask and tblrcmtaskoptions respectively.
I do not understand how do I create new ID in both the tables while the user adds new entries.The user can add only tblrcmtaskoptions.rcmtaskoptions and tblrcmtask.rcmtask in the form.Also, there are multiple rows in the table tblrcmtaskoptions for each tblrcmtask.id.
I want the user to be able to add new rows in the table tblrcmtaskoptions for an existing tblrcmtask.id
I tried using dropdowns for these two but I am facing problem while creating the new ID as Maximum of the ID + 1.
Dim MyRecords As DAO.Recordset
Dim Myfield As DAO.Fields
SQL = "SELECT Max(tblRCMTASK.ID) AS MaxOf_RCMTASKID FROM tblRCMTASK;"
Set MyRecords = dbTHIS.OpenRecordset(SQL)
Set Myfield = MyRecords.Fields
Me.txtRCMTASKID = Myfield("MaxOf_RCMTASKID") + 1
Me.txtRCMTASKID.DefaultValue = Myfield("MaxOf_RCMTASKID") + 1
MyRecords.Close
End If
Dim MyRecords1 As DAO.Recordset
Dim Myfield1 As DAO.Fields
SQL = "SELECT Max(tblRCMTASKOPTIONS.ID) AS MaxOf_RCMOPTIONSID FROM tblRCMTASK;"
Set MyRecords = dbTHIS.OpenRecordset(SQL)
Set Myfield1 = MyRecords1.Fields
Me.txtRCMOPTIONSID = Myfield1("MaxOf_RCMOPTIONSID") + 1
Me.txtRCMOPTIONSID.DefaultValue = Myfield("MaxOf_RCMOPTIONSID") + 1
MyRecords1.Close
I am getting an error which says you can't asign a value to this object and points to this line: Me.txtRCMTASKID = Myfield("MaxOf_RCMTASKID") + 1
How do I do this?

Access gives you trouble when trying to do operations on an autonumber field. If you would like to do these kinds of operations, you may be better off just using a regular number as a PK.
To get a recently inserted autonumber field to insert the same number in a related table, this is the VBA:
assuming recordset and database are declared, rs and db
dim id as integer
set db = CurrentDb
set rs = db.openrecordset("firstTable", dbOpenDynaSet)
With rs
.addNew
.Fields("field1").Value = Me.control1 'adds to column1 of your table the value of control1
.Fields("field2").Value = Me.control2
.update 'updates the record. If it is an autonumber, it will be automatically assigned. I will show you how to access this for your next insert
end with
'To get the autoID of the entry we just inserted, do this
id = db.OpenRecordSet("SELECT##IDENTITY")(0)
'Now you have the autoID of the recent insertion, so you may use it for your next one.

This is a classic form/subform set up. Create a form based solely on tblrcmtask with a subform tblrcmtaskoptions. The link child and master fields should be set to the common id. The wizards will do this for you. There is no code required. The id will be automatically added by the link fields.
You can see an example for in the 2007 version of the Northwind sample database.

Related

Access 2016: Entering multiple values in a cell and saving it as multiple records in the same table

I have imported an existing excel file and created it as table 'Product' in access. It already has rows of existing data. I have created a form based on the table for data entry.
I would like to enter multiple values in the ProductNo cell separated by a comma ( as shown below)
PID (PK - Autonum)
PCR
ProductNo
Title
Unit
Dept
Date
Comments
PCR1
p210en, p213es, p217er
PCR1 title description
2
D1
1/23/21
fdsfsdf
and saving the record, it has to split the cell values and save it as multiple records in the backend product table.
PID (PK - Autonum)
PCR
ProductNo
Title
Unit
Dept
Date
Comments
PCR1
p210en
PCR1 title description
2
D1
01/23/2021
fdsfsdf
PCR1
p213es
PCR1 title description
2
D1
01/23/2021
fdsfsdf
PCR1
p217er
PCR1 title description
2
D1
01/23/2021
fdsfsdf
I don't want to edit the existing data in Product. It correctly reflects only one value in the ProductNo. I want to update only the values entered in the form.
I have looked for similar vba codes and found ones that modifies data in the existing table.
I have worked with SQL before but not much with Access/VBA code. I have programming knowledge. Any help is appreciated. Thank you :)
Updated -- Possible Solution:
So this is what I have done. I have a created a temporary table 'TempProduct' that I have used to input the data and when I click on save button, I have the following vba code that splits the cell data in multiple records and adds it to the original table.
enter code here
Option Compare Database
Private Sub Command11_Click()
Dim db As Database
Dim rs1 As Recordset
Dim rs2 As Recordset
Set db = CurrentDb()
Dim sqlStr, fieldStr As String
Dim i As Integer
sqlStr = "Select PCR, ProductNo, Title, Unit, Dept, Date, Comments from TempProduct"
Set rs1 = db.OpenRecordset(sqlStr)
Set rs2 = db.OpenRecordset("Product")
Do While Not rs1.EOF
fieldStr = rs1.Fields(1)
If InStr(fieldStr, ",") > 0 Then
myString = Split(fieldStr, ",")
For i = LBound(myString) To UBound(myString)
rs2.AddNew
rs2!PCR = rs1!ECRNo
rs2!ProductNo = myString(i)
rs2!Title = rs1!Title
rs2!Unit = rs1!Unit
rs2!Dept = rs1!Dept
rs2!Date = rs1!Date
rs2!Comments=rs1!Comments
rs2.Update
Next i
Else
rs2.AddNew
rs2!PCR = rs1!ECRNo
rs2!ProductNo = rs1!ProductNo
rs2!Title = rs1!Title
rs2!Unit = rs1!Unit
rs2!Dept = rs1!Dept
rs2!Date = rs1!Date
rs2!Comments=rs1!Comments
rs2.Update
End If
rs1.MoveNext
Loop
DoCmd.RunSQL ("Delete * from TempProduct")
End Sub
And it kind of works. Though the multiple records are pushed from the form into the product table only when a new record is added again. i.e. the first record entered in the form are split and entered into the product table only after the second set of records are entered in the form.
Any suggestions as how I can push the records immediately. Thanks a bunch.

Looping through a recordset to retrieve values

returnAddress = "SELECT Address_ID FROM Address_Bridge WHERE Customer_ID =
76541 AND Company_ID = 23540"
set db = currentDB
set rst = db.openRecordSet(returnAddress)
This is my recordset. It returns all address IDs for a specific combination of Customer and Company. I anticipate there being anywhere from 1 to 7 Address IDs being returned by this recordset. I need to use each of them as values in an Append query. I'm just not sure how to access them.
For Each Address_ID in rst
perform update query
next
That's my assumption of how to do it, but I've tried several variations and all have returned errors. If anyone could assist me with the specific syntax for this, it would really be appreciated!
Here is how I do it.
Dim sValue As String
Do until rst.EOF
sValue=rst!FieldName
' do other stuff
rst.MoveNext
Loop

DLookup Or DMax To Find Value

I am sure this is fairly simple put I am having trouble getting started on this. I use a Form to invoice clients which includes the field [Billing_Month]. What I'm looking to accomplish is this. When I create a new invoice, the [Billing_Month] will look to the last invoice created (use [Invoice_#] with DMax?), and populate the value from that that invoices [Billing_Month]
I have thought to use: Billing_Month = DMax ("Billing_Month", "frmInvoices"), but this doesn't specifically get me the last invoice, it would just look for the highest Billing_Month, which is a text field.
I have thought to use: Billing_Month = DLookup ("Billing_Month", "frmInvoices"), But this doesn't get me the last invoice to pull from.
I'd use a custom function for this - assuming the underlying table is called tblInvoices:
Function GetBillingMonthOfLatestInvoice()
Const SQL = "SELECT TOP 1 Billing_Month FROM tblInvoices ORDER BY [Invoice_#] DESC"
Dim RS AS DAO.Recordset
Set RS = CurrentDb.OpenRecordset(SQL)
If RS.EOF Then
GetBillingMonthOfLatestInvoice = Null
Else
GetBillingMonthOfLatestInvoice = RS(0)
End If
End Function
Update
The above code can be generalised to return other related fields like so:
Function GetValueForLatestInvoice(FieldToLookUp As String)
Dim RS As DAO.Recordset, SQL As String
SQL = "SELECT TOP 1 " + FieldToLookUp + " FROM tblInvoices ORDER BY [Invoice_#] DESC"
Set RS = CurrentDb.OpenRecordset(SQL)
If RS.EOF Then
GetValueForLatestInvoice = Null
Else
GetValueForLatestInvoice = RS(0)
End If
End Function
To use, copy the code to a new standard module, then for each relevant text box on the form, set its Default Value property in the Properties window to something like this:
=GetValueForLatestInvoice("Billing_Month")
That would be for the text box holding the billing month value; for the one holding the billing year, you would use
=GetValueForLatestInvoice("Billing_Year")
You can use a combination of both DLookup() and DMax() like so:
DLookup("Billing_Month","tblInvoices","[Invoice_#]=" & DMax("[Invoice_#]","tblInvoices"))

vb.net how to create a variable to count entries going in as inserts and updates

I have a mysql database and a gridview. Now I want to count my inserts and updates. It has been suggested to set up a variables to represent each element e.g. nUpdates and nInserts, but I am unsure on how to do this? Here is the code I am using
For i = 0 To DataGridView1.RowCount - 1
Using dbSQL_cmd As New MySqlCommand()
student_id = DataGridView1.Item(i, 0).Value.ToString
name = DataGridView1.Item(i, 1).Value.ToString
age = DataGridView1.Item(i, 2).Value.ToString
adress = DataGridView1.Item(i, 3).Value.ToString.ToLower
dbSQL_query = "INSERT INTO student VALUES (?id, ?name, ?age, ?adress) " +
" on duplicate key update name=(name=?name, age=?age, adress=?adress)"
With dbSQL_cmd
.Parameters.AddWithValue("?id", student_id)
.Parameters.AddWithValue("?name", name)
.Parameters.AddWithValue("?age", age)
.Parameters.AddWithValue("?adress", adress)
' .Parameters.AddWithValue("?status", ?????)
.CommandText = dbSQL_query
.Connection = SQLConnection
.CommandType = CommandType.Text
End With
dbSQL_cmd.ExecuteNonQuery()
End Using
Next
First, check the number of rows in the table before and after your insert/update loop. The difference between them is the number of rows you inserted.
You know how many items there are in your gridview. From your code, each one is either an insert or an update, so subtract the number of inserts you did (from that first step) from the number of items, and that is the number of rows you updated.

Create a field name from a recordset

I have a form that displays information on a project that has 10 check boxes. The check boxes are named "chkAudience1", "chkAudience2", etc through "chkAudience10". Any combination of boxes can be checked from none to all and anything in between.
Then I have a table that links the check boxes to the project. This table contains a field called ProjectID and a field called AudienceID (both fields are defined as number). This allows me to select all audience records for a project.
The problem is that I want to loop through the records for a project and check the boxes that match a record in the table. My current code looks like:
sqlStmt = "SELECT * FROM ProjectAudience WHERE ProjectID = " & Me.ProjectID.Value
Set rs = cn.Execute(sqlStmt)
While Not rs.EOF
'Me.chkAudience1.Value = -1
x = "Me.chkAudience" & rs(1).Value
x.Value = -1
rs.MoveNext
Wend
x will be set to "Me.checkAudience1", but the next line produces an "object required" error. How do I create a field name based on recordset data and then use that field name to set a value. (This is being done is Microsoft Access 2003)
The correct while loop is:
While Not rs.EOF
'Me.chkAudience1.Value = -1
Me.Controls("chkAudience" & (rs(1).Value)).Value = -1
rs.MoveNext
Wend
The key is the Me.Controls().