Insert textbox value from a form into a table - vba

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 & "')"

Related

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

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.

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.

insert statement error vb.net

following is the code which is use to enter datagridview items into the table.
Dim X As DataGridViewRow
grnno = 123123
glocation = txtlocation.Text
gsupplier = txtsupplier.Text
greceivedby = txtreceivedby.Text
greceiveddate = txtreceiveddate.Text
grn_status = cmbstatus.SelectedItem
ggrossamt = txtgrossamt.Text
gdiscountamount = txtdiscount.Text
gtotalnetamount = txttotalnet.Text
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) values('" & glocation & "','" & gsupplier & "','" & greceivedby & "','" & greceiveddate & "','" & grn_status & "'," & ggrossamt & "," & gdiscountamount & "," & gtotalnetamount & " )"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "','" & X.Cells(6).Value & "','" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
Next
the error is in the 2nd insert statement, it gives error cannot convert string to integer.. the cells from x.cell(6) are of integer type and in database also its integer type, now I want to ask should I enclose it in single quotations or not, as enclosing in single quotations give such errors like syntax '' and in double quotations it gives like cannot convert string to int type.please tell where I am doing wrong.
First of all use parametrized queries! It is safer and also more readable. You are passing some value as string but should be integer.
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) _
values(#glocation, #gsupplier, #greceivedby, #greceiveddate, #grn_status, #ggrossamt, #gdiscountamount, #gtotalnetamount)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#glocation", glocation)
sqlcmd.Parameters.AddWithValue("#gsupplier", gsupplier) //and so on
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) _
VALUES(#grnno, #item_code, #description, ...)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#grnno", grnno)
sqlcmd.Parameters.AddWithValue("#item_code", CType(X.Cells(0).Value, Integer)) //cast to proper type
sqlcmd.ExecuteNonQuery()
Next
Remove the single quote marks ''
For example (and referring only to x.cell(6) as per your post) use " & X.Cells(6).Value & "
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & X.Cells(6).Value & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
You may also need to cast it (assuming it's always going to have a numeric value)
" & CInt(X.Cells(6).Value) &"
I will assume you know of SQL injection and this method of updating a database is generally 'outdated' and 'bad practice' now and you should use parameters instead...
Updated
Since there is a possibility of a null (and you want it to be a 0 where this is the case), you could use something like (not tested as I'm not a VB person)
dim cellSix as integer
if IsNothing(X.Cells(6).Value then
cellSix = 0
else
cellSix = CInt(X.Cells(6).Value)
end if
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & cellSix & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
Or, to keep the code shorter you could use the IIF
cellSix = IIf(isnothing(CInt(X.Cells(6).Value)), 0, CInt(X.Cells(6).Value))

Microsoft Access 2010 VB InsertInto syntax error

I am totally new to Microsoft Access and VB, what i am trying to do is i have a form with unbounded textboxes which i would like upon clicking a button save the text in each textbox in its unique field.
I managed to write this piece of code with some help from online resources but it keeps giving me syntax error, if someone could point me into the correct way.
CurrentDb.Execute "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"IT-DEC-MAKER-FNAME, IT-DEC-MAKER-LNAME) " & _
"VALUES('" & Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & _
Me.qjob & "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & _
Me.qfax & "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
Since are IT-DEC-MAKER-FNAME and IT-DEC-MAKER-LNAME are invalid identifiers in SQL, you must enclose them in brackets ([ ])
CurrentDb.Execute "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"[IT-DEC-MAKER-FNAME], [IT-DEC-MAKER-LNAME]) " & _
"VALUES('" & Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & _
Me.qjob & "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & _
Me.qfax & "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
UPDATE:
I have two nice helper functions for this kind of things.
This one replaces placeholders in a string with values
Function Build(ByVal s As String, ParamArray args()) As String
' Build("LastName = {0}, FirstName = {1}","Dow","John") --> "LastName = Dow, FirstName = John".
' "\n" will be converted to vbCrLf.
Dim i As Long
s = Replace(s, "\n", vbCrLf)
For i = 0 To UBound(args)
s = Replace(s, "{" & i & "}", Nz(args(i)))
Next i
Build = s
End Function
This one converts a variant value supposed to contain a text in to a SQL value
Public Function SqlStr(ByVal v As Variant) As String
' NULL Returns: NULL
' "" Returns: NULL
' "abc" Returns: 'abc'
' "x'y" Returns: 'x''y'
Dim s As String
s = Nz(v)
If s = "" Then
SqlStr = "NULL"
Else
SqlStr = "'" & Replace(s, "'", "''") & "'"
End If
End Function
You can then use them like this making your code safer and easier to understand.
Dim template As String, sql As String
template = "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"[IT-DEC-MAKER-FNAME], [IT-DEC-MAKER-LNAME]) " & _
"VALUES({0},{1},{2},{3},{4},{5},{6},{7},{8},{9});"
sql = Build(template, _
SqlStr(Me.qfirstname), SqlStr(Me.qlastname), _
SqlStr(Me.qjob), SqlStr(Me.qphone), _
SqlStr(Me.qmobile), SqlStr(Me.qemail), _
SqlStr(Me.qfax), SqlStr(Me.qitfirstname), _
SqlStr(Me.qitlastname))
CurrentDb.Execute sql
I suggest you lay out your code like so:
sSQL = "INSERT INTO UserInformation(" _
& "FirstName, LastName, Company, JobTtile, " _
& "PhoneNumber, Mobile, Email, Fax, " _
& "IT-DEC-MAKER-FNAME, IT-DEC-MAKER-LNAME) " _
& "VALUES('" _
& Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & Me.qjob _
& "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & Me.qfax _
& "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
CurrentDB.Execute sSQL, dbFailOnError
It makes it much easier to see mistakes and the sSQL string can be printed to the immediate window for debugging. You will see you have JobTtile.
It is usually better to use an instance of CurrentDB:
Dim db As DAO.Database
Set db = CurrentDB
I wonder why you do not just bind a recordset?