MS Access Rollback error handling Rollback - error-handling

In my Programm I have a fucntion that does three thing: It makes several inserts in some tables, it creates a pdf document and it sends an e-mail with the created document in the attachment. I have a problem resolving the error handling.
DAO.DBEngine.BeginTrans
On Error GoTo failed
CurrentDb.Execute "INSERT INTO tblClaimStatus ( ClaimID, ClaimStatusTypeID, UserID) " & _
"VALUES (" & claimId & ", 2," & CurrentUserId & ");", dbFailOnError
CurrentDb.Execute "Insert INTO tblClaimPartner (ClaimId, OriginalDeadline, NachfristDeadline) " & _
"VALUES (" & claimId & ", '" & Me.OriginalDeadlineTextbox & "', '" & Me.NewDeadlineTextbox & "');", dbFailOnError
WriteGraceDocument (claimId)
SendEmail (claimId)
DAO.DBEngine.CommitTrans
The problem is I want to be able to rollback the SQL-transaction, if anything fails. But I also need the not yet committed data in the Subs WriteGraceDocuement and SendEmail.
How should I solve this?

Let your functions return success or no success:
DAO.DBEngine.BeginTrans
' Validate the values before attempting to insert these.
Success = ValidateInserts(claimId, 2, CurrentUserId, Me!OriginalDeadlineTextbox.Value, Me!NewDeadlineTextbox.Value)
If Success Then
CurrentDb.Execute "INSERT INTO tblClaimStatus ( ClaimID, ClaimStatusTypeID, UserID) " & _
"VALUES (" & claimId & ", 2," & CurrentUserId & ");", dbFailOnError
CurrentDb.Execute "Insert INTO tblClaimPartner (ClaimId, OriginalDeadline, NachfristDeadline) " & _
"VALUES (" & claimId & ", '" & Me.OriginalDeadlineTextbox & "', '" & Me.NewDeadlineTextbox & "');", dbFailOnError
End If
If Success Then
Success = WriteGraceDocument(claimId)
End If
If Success Then
Success = SendEmail (claimId)
End If
If Success Then
DAO.DBEngine.CommitTrans
Else
DAO.DBEngine.RollBack
End If

Related

Run-time error ‘3061’: Too few parameters expected 1

i had this error when i was trying to INSERT records to a local table with VBA.
I have checked the data type and putting in the quotes for the the short text data type but it doesn't work.
table_newid = "SELECT Cint(t1." & id_name(i) & "_new), " & Replace(select_column_str, local_table_name, "t2") & " FROM " & vbCrLf & _
"(SELECT CInt(DCount(""[" & id_name(i) & "]"", """ & qry_distinct_id_name & """, ""[" & id_name(i) & "]<="" & [" & id_name(i) & "])) as " & id_name(i) & "_new, * FROM " & qry_distinct_id_name & ") AS t1 " & vbCrLf & _
"LEFT JOIN " & local_table_name & "_ALL as t2 " & vbCrLf & _
"ON t1." & id_name(i) & " = t2." & id_name(i) & " " & vbCrLf & _
"WHERE t2.database = '" & database_name & "'"
strQuery = "INSERT INTO " & local_table_name & "_temp (" & temp_field(i) & ", " & Replace(select_column_str, local_table_name & ".", "") & ") " & vbCrLf & table_newid
Debug.Print strQuery
DoCmd.SetWarnings False
db.Execute strQuery
DoCmd.SetWarnings True
From the debug.print, i have got:
INSERT INTO TblLUMachineTypes_temp (MachTypeID_new, MachTypeID, MachTypeCode, MachTypeMod, MachTypeDesc, MachTypeDisc, NewCode, Approved, mttime, CreatedBy, CreatedTS, ModifiedBy, ModifiedTS)
SELECT t1.MachTypeID_new, t2.MachTypeID, t2.MachTypeCode, t2.MachTypeMod, t2.MachTypeDesc, t2.MachTypeDisc, t2.NewCode, t2.Approved, t2.mttime, t2.CreatedBy, t2.CreatedTS, t2.ModifiedBy, t2.ModifiedTS FROM
(SELECT CInt(DCount("[MachTypeID]", "qry_TblLUMachineTypes_id_distinct", "[MachTypeID]<=" & [MachTypeID])) as MachTypeID_new, * FROM qry_TblLUMachineTypes_id_distinct) AS t1
LEFT JOIN TblLUMachineTypes_ALL as t2
ON t1.MachTypeID = t2.MachTypeID
WHERE t2.database = 'CPM-252-2'
When i copied this query and execute it manually, it works fine but not with VBA. Any idea?
Thanks in advance.
Remove all the & vbCrLf from your code, they are not necessary and I assume they corrupt the SQL syntax.
I found the problem. I found that qry_distinct_id_name query table has a Dlookup function in there that returns a string value, which will work when executing the query manual but doesn't work when you run it with VBA. So I have re-written the code to put in the quote before and after dlookup() function.

When I write code inside textbox doesn't accept it

I have a textbox in a form. I use this textbox to write "Codes" and then I save it in the table in the database through the SQL insert statement, but the code doesn't accept to run and gives me an error message:
Run-Time error '3075'.
type of database: Access database
type of field data: LongText
What the problem and how to pass all same problems when I need to save codes inside the database field.
When I try to save the code without (') it's working!
I use this SQL Statement:
CurrentDb.Execute "Update Tbl_Codes Set [LP_ID]= " & Me.txtID & ",
[Code_Title]='" & Me.txtTitle & "'" _
& " ,[Code_Des]= '" & Me.txtDes & "',[Code_Key]= '" & Me.txtKey & "',
[Notes]= '" & Me.txtNotes & "'" _
& " Where [ID]= " & Me.txtID1 & ""
And I want to save this Code:
DSum("Field1";"Table";"Field2= '" & Value & "'")
Please change your code as follows. You need to escape single quotes by doubling them up. A simple replace will work for your.
CurrentDb.Execute "Update Tbl_Codes Set [LP_ID]= " & Replace(Me.txtID,"'","''") & ",
[Code_Title]='" & Replace(Me.txtTitle,"'","''") & "'" _
& " ,[Code_Des]= '" & Replace(Me.txtDes,"'","''") & "',[Code_Key]= '" & Replace(Me.txtKey,"'","''") & "',
[Notes]= '" & Replace(Me.txtNotes,"'","''") & "'" _
& " Where [ID]= " & Me.txtID1 & ""
DSum("Field1";"Table";"Field2= '" & Replace(Value,"'","''") & "'")

Missing comma error error inserting sql through access 2010 vba

Having the weirdest problem ever. I do have an sql insert statement, that properly works in sql. When i put that sql into vba it works very good from my pc. However, it does not work and shows sql error: missing comma. Where can be the problem??? I use Access 2010 plus, others use same Access version and having same ODB connections (DSN servers) . Some code example:
sql = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST= ODB)(PORT=1520))" & _
"(CONNECT_DATA=(SERVICE_NAME=ABTL))); uid=IN; pwd=XXX;"
Set con = New ADODB.Connection
Set rec = New ADODB.Recordset
Set cmd = New ADODB.Command
con.Open sql
Set db = CurrentDb()
Set rst = db.OpenRecordset(strSQL)
Do While Not rst.EOF
insetSQL = con.Execute(" INSERT INTO STOCK (PNM_AUTO_KEY, PN, DESCRIPTION, HISTORICAL_FLAG, qty_oh, qty_adj, qty_available, CTRL_NUMBER, CTRL_ID, receiver_number, rec_date, serial_number,pcc_auto_key, cnc_auto_key, loc_auto_key, whs_auto_key, unit_cost, adj_cost, stc_auto_key, visible_mkt, remarks, ifc_auto_key, exp_date, unit_price, tagged_by, tag_date, owner, PART_CERT_NUMBER,ORIGINAL_PO_NUMBER, SHELF_LIFE, CTS_AUTO_KEY, MFG_LOT_NUM, AIRWAY_BILL )" & _
" VALUES ( " & rst![minimumas] & ", '" & rst![pn] & "', '" & "FROM_SCRIPT" & "', '" & "F" & "'," & rst![qty_oh] & "," & rst![qty_oh] & "," & rst![qty_oh] & "," & "G_STM_CTRL_NUMBER.nextval" & "," & "1" & ", '" & rst![receiver_number] & "', " & " TO_DATE('" & rst![rec_date] & "','YYYY-MM-DD'), '" & rst![serial_number] & "'," & rst![pcc_auto_key] & "," & rst![cnc_auto_key] & "," & rst![loc_auto_key] & "," & rst![whs_auto_key] & "," & rst![unit_cost] & "," & rst![unit_cost] & "," & "1" & ",'" & "T" & "', '" & rst![remarks] & "'," & _
"1" & ", " & " TO_DATE('" & rst![exp_date] & "','YYYY-MM-DD'), " & "0" & ",'" & rst![TAGGED_BY] & "', " & " TO_DATE('" & rst![tag_date] & "','YYYY-MM-DD'), '" & "" & "', '" & rst![PART_CERT_NUMBER] & "', '" & rst![ORIGINAL_PO_NUMBER] & "', '" & rst![SHELF_LIFE] & "', " & rst![CERT_SOURCE] & ", '" & rst![MFG_LOT_NUM] & "', '" & rst![AIRWAY_BILL] & "'" & " )")
Loop
It might be that one of the rescordset fields that is a string data type, has a value that contains a comma but you have not treated it as string.
eg
VALUES ( " & rst![minimumas] & ",
For the above code to work minimumas CANNOT contain any commas.
Are you certain that all the string fields int he recordset have been appended to the SQL string with a ' around them.
We need to see the sql string is created which then causes the error. Please provide this as requested.
=========================================================
PART 2 Viewing the SQL causing the error
replace
insetSQL = con.Execute(
with
on error resume next
strMySQl = the string currently used in the execute statement
insetSQL = con.Execute(strMySQl)
if err.number <> 0 then
stop
debug.print err.number, err.description
debug.print strMySQl
end if
then post the sql string that is printed in the immediate window to this site.
I would also suggest that you compare the SQL string generated on your machine with the other machines - just in case something weird is happening.

error 3075 syntax missing comma

I've looked in many places on the internet trying to solve this problem but I can't seem to figure it out. Could someone just provide a second set of eyes and just check where I may have gone wrong with the syntax?
The error says RunTime error 3075,
"Syntax error (comma) in query expression
'('test',12/15/2014','Primary')'.
Originally it worked when I had this split into four different INSERT statements, but when I combined it, it stopped working
SQL = "INSERT INTO WeeksonCall([Employee], [Week], [Prim/Backup]) VALUES (('" & _ cboName.Column(1) & "','" & cboWeek.Column(1) & "','" & cboPrimBack.Value & _
"'),('" & cboName2.Column(1) & "','" & cboWeek.Column(1) & "','" & cboPrimBack2.Value & _
"'),('" & cboName.Column(1) & "','" & cboWeek2.Column(1) & "','" & cboPrimBack2.Value & _
"'),('" & cboName2.Column(1) & "','" & cboWeek2.Column(1) & "','" & cboPrimBack.Value & "'))"
That is not proper syntax in MS Access. You will have to insert the records individually like:
DoCmd.SetWarnings False
SQL = "INSERT INTO WeeksonCall(Employee, Week, [Prim/Backup]) " & _
"VALUES ('" & _ cboName.Column(1) & "','" & cboWeek.Column(1) & "','" & cboPrimBack.Value & "')"
SQL = "INSERT INTO WeeksonCall(Employee, Week, [Prim/Backup]) " & _
"VALUES ('" & cboName2.Column(1) & "','" & cboWeek.Column(1) & "','" & cboPrimBack2.Value & "')"
SQL = "INSERT INTO WeeksonCall(Employee, Week, [Prim/Backup]) " & _
"VALUES ('" & cboName.Column(1) & "','" & cboWeek2.Column(1) & "','" & cboPrimBack2.Value & "')"
SQL = "INSERT INTO WeeksonCall(Employee, Week, [Prim/Backup]) " & _
"VALUES ('" & cboName2.Column(1) & "','" & cboWeek2.Column(1) & "','" & cboPrimBack.Value & "')"
DoCmd.SetWarnings True
EDIT: You can stop the user prompts by using SetWarnings = False before the inserts. Then turn the warnings back on after the inserts via DoCmd.SetWarnings True.
Can you please provide the remainder of the VBA you're using in order to ask the user for input? As far as I see you're only assigning a string to the SQL variable. Where is the rest of your code?
And, by the way, I never like using:
DoCmd.SetWarnings False
Instead use the module below, that way if you do get an error you can deal with it instead of hidding it:
Option Compare Database
Option Explicit
Public Function Run_Safe_SQL(strSQL)
On Error GoTo Error_Handler
Dim db As DAO.Database
Set db = CurrentDb()
db.Execute strSQL, dbFailOnError
DBEngine.Idle dbRefreshCache
' DoEvents
Exit_Here:
'Cleanup
Set db = Nothing
strSQL = ""
Exit Function
Error_Handler:
MsgBox Err.Description & " " & Err.Number
End Function

3134 run time error on Insert into statement

I am trying to write a form to insert data into multiple tables within a single database.
I know you can't do that through a single Insert into statement so I read that I should create a transaction and include multiple Insert statements. I keep getting 3134 run time error on my second insert statement. Here is the code:
Private Sub cmdAdd_Click()
DBEngine.BeginTrans
CurrentDb.Execute "INSERT into Names(StudentId, FirstName, MiddleName, LastName) VALUES (" & Me.txtStudentId & ",'" & _
Me.txtFirstName & "','" & Me.txtMiddleName & "','" & Me.txtLastName & "')"
CurrentDb.Execute "INSERT into Homeroom(StudentId, Grade, Homeroom_Primary, Name-Homeroom_Primary_Teacher) " & _
"VALUES (" & Me.txtStudentId & ",'" & Me.txtGrade & "','" & Me.txtHomeroom & "','" & Me.txtTeacher & "')"
CurrentDb.Execute "INSERT into [Ridgeview Math](StudentId, ExportGrade, DateTaken, SS, PR) VALUES (" & _
Me.txtStudentId & ",'" & Me.txtGrade & "',#" & Me.txtMathdate & "#,'" & Me.txtMathSS & "','" & Me.txtMathPR & "')"
CurrentDb.Execute "INSERT into [Ridgeview Reading](StudentId, ExportGrade, DateTaken, RSS, RPR, RIRL) " & _
"VALUES (" & Me.txtStudentId & "','" & Me.txtGrade & "',#" & Me.txtReadingdate & "#,'" & Me.txtReadingSS & "','" & _
Me.txtReadingPR & "','" & Me.txtReadingIRL & "')"
CurrentDb.Execute "INSERT into CompassGroup(StudentId, CompassGroup) VALUES (" & Me.txtStudentId & _
"," & Me.txtCompassGroup & ")"
DBEngine.CommitTrans
End Sub
Am I doing something wrong with the nested Insert statements?
This is all tied to a form where the variables are created and the data is entered. The first Insert statement gives me no errors. Please let me know if you need more information.
Bracket the field name Name-Homeroom_Primary_Teacher because of the dash.
I suggest you use a string variable to hold the statement text, Debug.Print the string, and then Execute it.
Dim strInsert As String
strInsert = "INSERT into Homeroom(StudentId, Grade, Homeroom_Primary, [Name-Homeroom_Primary_Teacher]) " & _
"VALUES (" & Me.txtStudentId & ",'" & Me.txtGrade & "','" & Me.txtHomeroom & "','" & Me.txtTeacher & "')"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailonerror
If case of errors, you can go to the Immediate window (Ctrl+g) to inspect the statement text. And you can copy that text, create a new query in the query designer, switch to SQL View, paste in the text, and test the statement there.
Also the approach you're using requires a whole lot of concatenating. Other options you can consider are: parameter queries; adding rows to DAO Recordsets.