MS Access and Visual Basic - syntax error in insert into statement - vba

I get this error when I want to send data from form into table. This is Visual Basic code I wrote in MS Access:
Private Sub btnAdd_Click()
CurrentDb.Execute "INSERT INTO Book(book_id,title,language_id,author_id,year_published,num_pages,publisher_id,num_copies)" & _
"Values (" & Null & ",'" & Me.txtTitle & "','" & Me.cbLanguage.Column(0) & "','" & Me.cbAuthor.Column(0) & "','" & Me.txtYearPublished & "','" & _
Me.txtNumPages & "','" & Me.cbPublisher.Column(0) & "','" & Me.txtNumCopies & "')"
End Sub
book_id is the primary key and auto-number.
Arrow indicating error appears on the 4th line of code.

Your main issues are because Book_ID is set to Auto Number type; it does not need to be passed, Access JET engine will take care of it for you. Then all your values are Numeric, but when you add a ' to the variable you treat it as String/Text. So your code needs to change as,
Private Sub btnAdd_Click()
CurrentDb.Execute "INSERT INTO Book (title, language_id, author_id, year_published, " & _
"num_pages, publisher_id, num_copies) VALUES (" & Me.txtTitle & ", " & _
Me.cbLanguage.Column(0) & ", " & Me.cbAuthor.Column(0) & ", " & Me.txtYearPublished & _
", " & Me.txtNumPages & ", " & Me.cbPublisher.Column(0) & ", " & Me.txtNumCopies & ")"
End Sub

Just don't include book_id anywhere in the insert statement if it's PK and auto-incremented.

Related

Insert textbox value from a form into a table

I have a textbox(in form) and a field(in table) both named SerialNumber
This is the control source of the textbox: =([OrderNr] & (""+[Aantal]) & "" & [SapArtNr])
I can't seem to make the textbox save the value inside into the table.
Edit:
Option Compare Database
Private Sub Command82_Click()
' Add data to Table
CurrentDb.Execute "INSERT INTO Geleidelijst(SerialNmbr, InvoerOrderNr, InvoerAantal, InvoerVermogen, InvoerHSLSSpn) " & _
" VALUES(" & Me.SerialNumberLong & ",'" & Me.OrderNr & "','" & _
Me.Aantal & "','" & Me.Vermogen & "','" & Me.HSLSSpn & "')"
End Sub
But then I get error: 3075 Synax error missing operating in query expression. And if I add date as a format it doesn't work either.
Only when it's numbers, but when there's letters and dots and "/" for example, it won't work.
Any help would be nice, thanks.
Most likely, Aantal is numeric, so try without quotes:
CurrentDb.Execute "INSERT INTO Geleidelijst " & _
"(SerialNmbr, InvoerOrderNr, InvoerAantal, InvoerVermogen, InvoerHSLSSpn) " & _
"VALUES('" & Me.SerialNumberLong & "','" & Me.OrderNr & "'," & Me.Aantal & ",'" & Me.Vermogen & "','" & Me.HSLSSpn & "')"

Insert statement terminated in VB6 [error 01000 Microsoft ODBC] when using Windows 10

My VB6 application runs OK in Windows 7 but generates an error in Windows 10. The error message is:
error 01000: microsoft ODBC
When I debug in Windows 10, Windows can't execute my insert statement. My ODBC connection is OK. I think Windows 10 can't handle long statement. Please help me solve this problem.
This is the code to save and insert data into database:
Set InsertData = New rdoQuery
Set InsertData.ActiveConnection = conndtrs
InsertData.SQL = "insert into downtime (dt_date,dt_info1,dt_shop,dt_shift, " & _
"dt_model,dt_region,dt_category,dt_sub_category,dt_time, " & _
"dt_details,dt_caseno,dt_responsible,day_night,dt_time1,user_id," & _
"dt_keyin,dt_meeting,Dt_Company,dt_ct_measure,area) " & _
" values ('" & Dt_Date & "','" & dt_info1 & "','" & dt_shop & "', " & _
"'" & dt_shift & "','" & dt_model & "','" & Dt_Region & "','" & dt_category & "', " & _
"'" & dt_sub_category & "'," & dt_time & ",'" & dt_details & "'," & newlk_caseno & ", " & _
"'" & dt_responsible & "','" & day_night & "','" & dt_time1 & "','" & user_id & "', " & _
"'" & dt_keyin & "','Y','PEMSB','" & dt_ct_measure & "','" & Area & "')"
InsertData.Execute
MsgBox ("Data saved.....")
Data is saved to a SQL 2000 database.
The problem arises in the insert query. May be the date format is wrongly specified. That is the reason this errors arises. Specify the date format as:-
Format(date,"dd/MMM/yyyy")
After turning on ODBC logging got the event message, A fatal error occurred while creating an SSL client credential. The internal error state is 10013. This did lead me to the fix from a similar error.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client\ Enabled needed to be flipped from 0 to 1

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

How to use a Form to Append a row to a table with Access 2010

I am attempting to create a simple "Add Record" form into my database. This is to add a NEW recordset. This data will need to be duplicated/added across three tables (although right now I am struggling to get it added to one table!
I have tried using an Append Query, but it will not pull the data from the form into the appended record. Here is my attempt at append query:
INSERT INTO Log ( State, Jurisdiction, Company, DueDate, Preparer )
SELECT Log.State, Log.Jurisdiction, Log.Company, Log.DueDate, Log.Preparer
FROM Log
WHERE (((Log.State)=[Forms]![NewEntry_Form]![TxtState]) AND
((Log.Jurisdiction)=[Forms]![NewEntry_Form]![TxtJurisdiction]) AND
((Log.Company)=[Forms]![NewEntry_Form]![TxtCoNo]) AND
((Log.DueDate)=[Forms]![NewEntry_Form]![TxtDueDate]) AND
((Log.Preparer)=[Forms]![NewEntry_Form]![TxtPrep]));
I don't understand where I am going wrong. Would it be easier to write a VBA script to insert a new record then immediately update that record with the information from the form?
Thank you! I am very new at this.
Sarah
All you're doing is inserting a record from log into log if that record matches your form. Try this:
Sub InsertRecord()
Dim SQL As String
SQL = ""
SQL = SQL & "INSERT INTO Log ( State, Jurisdiction, Company, DueDate, Preparer )" & vbCrLf
SQL = SQL & "VALUES ("
SQL = SQL & Me.TxtState.Value & ", " & vbCrLf
SQL = SQL & Me.TxtJurisdiction.Value & ", " & vbCrLf
SQL = SQL & Me.TxtCoNo.Value & ", " & vbCrLf
SQL = SQL & Me.TxtDueDate.Value & ", " & vbCrLf
SQL = SQL & Me.TxtPrep.Value & ")"
CurrentDb.Execute SQL
End Sub
I ended up using VBA
Private Sub CmdAdd_Click()
'add data to table
CurrentDb.Execute "INSERT INTO FileInfo(Company, State, Jurisdiction, Taxtype, acctno, frequency, filemeth, pymtmeth, month, duedate, preparer, reviewer) " & _
" VALUES(" & Me.TxtCoNo & ",'" & Me.TxtState & "','" & Me.TxtJurisdiction & "','" & _
Me.TxtTaxType & "','" & Me.TxtAcctNo & "','" & Me.TxtFrequency & "','" & _
Me.txtFileMeth & "','" & Me.txtPymtMeth & "','" & _
Me.TxtMonth & "','" & Me.TxtDueDate & "','" & Me.TxtPrep & "','" & Me.TxtReviewer & "')"
FileInfosubform.Form.Requery

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.