Within VBA, in Access 2003, I need to
- Create a record in
TableA
with a new AutoNumber as the primary key (AID
) and the current date - Create several records in
TableC
which associateAID
from the new record inTableA
with multiple foreign keys (BID
) fromTableB
, as selected byQueryB
.
So if QueryB
returns records from TableB
with BID
s 2,5,7,8, I would then like to create a record in TableA
with AID = 1
and Date = 8/23/13
and then make TableC
appear thusly:
AID BID
---------
1 2
1 5
1 7
1 8
How do I do this? Accomplishing the first thing went fine until I remembered I needed a second field. Now my code reads:
Dim SQLstr As String
Dim db As DAO.Database
Set db = CurrentDb
SQLstr = "INSERT INTO TableA (FieldA, Date) "_
& "VALUES (list13.value, Date());"
db.Execute SQLstr
where List13
is a control in the open form (I can't change the name to something useful or it will no longer control the record displayed on the rest of the form). But once I added in FieldA
and list13.value
, I get an error message saying
Too few parameters. Expected: 1
I'm also not sure how to describe that I want to use the new record, (in this case, AID = 1
) to be the constant that all the QueryB
records are associated with. After a lot of searching, I think I want to use @@IDENTITY
, but I'm not sure how.
EDIT: I've finally gotten the following code to return AID properly:
Dim rs As DAO.Recordset
Dim AIDvar As Integer
Set rs = db.OpenRecordset("select @@identity")
AIDvar = rs(0)
And I was browsing over here and the following code was suggested for using INSERT INTO with a mix of field data and constants:
strText = "foo"
strInsertSQL = _
"INSERT INTO tblA(fld1, fld2, fld3) " _
& "Select fldA, fldB, '" & strText & "' AS Expr1 " _
& "From tblB ;"
So what I'm left with are the following questions:
What's wrong with using "list13.value" in my first code?EDIT: so, I fixed that with:strText = CStr(List13.Value) SQLstr = "INSERT INTO InvoiceT (AcctID, InvDate) "_ & "VALUES (" & strText & ", Date());"
But when I put it all together with the @@IDENTITY code, I get an overflow error. How do I get around that?
- What's the significance of "foo" in that code block I copied at the end?
- What's the significance of "AS Expr1" in the same code block?
- Will it work if I replace strText with AIDvar, from the @@IDENTITY code block?
- Why does "OpenRecordset" work if TableA is not actually open? Where is my thinking going wrong that this confuses me?