currentdb execute does not insert - ms-access

I'm having trouble with Access VBA. I made the following code to insert some data to my SQL DB.
Private Sub btnFilmKijkenKlant_Click()
CurrentDb.Execute "INSERT INTO watchhistory (movie_id, customer_mail_address, watch_date, price, invoiced) VALUES (" & movie_id.Value & ", '" & Me.txtEmail & "', Date(),'" & price.Value & "', '0')"
End Sub
When the user hits the button I want some data to be transferred to the DB.
I don't get any errors but it just doesn't insert...
I made txtEmail field for testing. I got an e-mail field in another form that I want to use as customer_mail_address.
When I include the dbFailOnError option with CurrentDb.Execute, Access complains "ODBC Call failed", but I don't understand why.

Dim db as Database
Set db = CurrentDb()
db.execute(......)

Related

Running an SQL string in VBA?

Iv created the SQL string sql in ms access vba but when it runs it prints the string in the debug window but doesn't actually run the string to add a record to the table like I want it to.
Public Sub EmpoyeesTable_Click()
Dim sql As String
sql = "INSERT INTO Employees " & _
"VALUES " & "(1, 'James', 'Dan', 'n6 indro Rd', 0943747, 30.24);"
Debug.Print sql
End Sub
Ultimately I want to use SQL strings to take input from a form when submit is clicked and add it to a table? Is this even the right approach?
There are many ways to run SQL strings in VBA. Each have their own advantages, and disadvantages. The most common ones are:
DoCmd.RunSQL sql
Runs the SQL just as it would if you executed a query. Popup will occur when you add, delete or modify records. You can use UDFs and form parameters
DoCmd.SetWarnings False
DoCmd.RunSQL sql
DoCmd.SetWarnings True
Disables warnings, then runs the SQL like in the previous way, then sets warnings back on.
CurrentDb.Execute sql
Executes the SQL over a DAO connection to the current database. You can't use UDFs and form parameters here. No warnings are shown. It just executes the SQL.
CurrentProject.Connection.Execute sql
Executes the SQL over an ADO connection to the current database. Very similar to the DAO connection, but there are subtle differences. For example, you can execute DDL statements that contain the Decimal data type, and set Check constraints in this way, while both are not allowed in any of the other ways.
You can read about using parameters with these different ways here. That's strongly recommended if you are going to insert values that aren't constant, to avoid bugs and SQL injection.
If you think simply then just change your Debug.Print sql to DoCmd.RunSQL (sql)
Private Sub Command0_Click()
Dim sql As String
sql = "INSERT INTO Employees " & _
"VALUES " & "(1, 'James', 'Dan', 'n6 indro Rd', 0943747, 30.24)"
DoCmd.RunSQL (sql)
End Sub
If you want take values from form then refer each value from form control like text box. See the below codes.
Private Sub Command0_Click()
Dim sql As String
sql = "INSERT INTO Employees VALUES (" & _
"'" & Me.Text1 & "'," & _
"'" & Me.Text2 & "'," & _
"'" & Me.Text3 & "'," & _
"'" & Me.Text4 & "'," & _
"'" & Me.Text5 & "'," & _
"'" & Me.Text6 & "');"
DoCmd.RunSQL (sql)
End Sub
If the field value is number type the you can remove singe quote (') from code for those field.

How to use "INSERT INTO" command from Access VBA to Sharepoint

I'm using a MS Access database linked with a Sharepoint Server. MS Access Forms as FrontEnd and Sharepoint Lists as BackEnd.
Today i can see all the informations from the lists using access forms, without problems.
What i need:
I'm trying to insert new registers on the list, using a SQL command: "INSERT INTO..."
if there is another possibility to insert the record in the list, may be useful
What's happening?
When i call the DoCmd.RunSQL(txtsql), i receive a runtime error 3999 saying i'm disconnected from the server.
My code now:
I tried using recordsets, but didn't succeed.
I need to run this SQL many times, changing the string "txtSql" inside a loop. Like this:
Dim MaxSonda As Integer
'Get the max ID from the list
MaxSonda = Nz(DMax("IdSonda", "Sondas", "((Sondas.[Tipo Sonda])<>1 Or (Sondas.[Tipo Sonda]) Is Null)"), 0)
MsgBox "MaxSonda = " & MaxSonda
'Run the code for each "sonda"
Do While MaxSonda > 1
If Nz(DLookup("[Tipo Sonda]", "Sondas", "Sondas!IdSonda = " & MaxSonda), 1) <> 1 Then
DoCmd.OpenTable "Resumo", acViewNormal, acAdd
DoCmd.GoToRecord acDataTable, "Resumo", acNewRec
txtSql = "INSERT INTO Resumo ( Data, Sonda, Status ) SELECT #" & LastData + 1 & "#, " & MaxSonda & ", 0;"
MsgBox txtSql
DoCmd.RunSQL txtSql
DoCmd.Close acTable, "Resumo", acSaveYes
End If
MaxSonda = MaxSonda - 1
Loop
P.S.: The MsgBox is just for check the steps
thanks for help
You don't need to open the list/table to insert a record. I don't know why you are using loop to insert rows but if that is your intention try this SQL_COMMAND within your loop:
If Nz(DLookup("[Tipo Sonda]", "Sondas", "[IdSonda] = " & MaxSonda), 1) <> 1 Then
txtSql = "INSERT INTO Resumo ( Data, Sonda, Status ) VALUES ('" & LastData + 1 & "'," & MaxSonda & ",0);"
MsgBox txtSql
DoCmd.RunSQL txtSql
End If
also note #tags are used to insert dates in Access, if you are intend to save dates save them in international format as strings like
vba.Format$([date_field],"yyyy-mm-dd hh:mm:ss")
this way you can just save as string without using the #tags.
Maybe this could help somebody. I did have the same problem and i solved it removing the sharepoint list from access and add it again. Take a seconds to make a sql query but it works.
greet

Getting the value from the first row where column name is <value>

I have a form where a user inserts some values
When the user clicks the "ok" button Access makes a new table to save the values from disappearing when the form closes.
strSQL = "CREATE TABLE tblTempProjectGegevens (Project varchar(32),ProjectNummer varchar(32), Opdrachtgever varchar(32));"
DoCmd.RunSQL (strSQL)
strSQL = "INSERT INTO tblTempProjectGegevens (Project, ProjectNummer, Opdrachtgever)" & _
"VALUES ('" & ProjectInvoer.Value & "', '" & ProjectNrInvoer.Value & "', '" & OpdrachtgeverInvoer.Value & "');"
DoCmd.RunSQL (strSQL)
DoCmd.OpenForm "frmMain", acNormal, , , acFormAdd
DoCmd.Close acForm, "frmProjectInvoer", acSaveNo
I save these values in a table, because my program requires the form to be closed.
When the user is done using my access file, there are some reports to be printed. On these reports are headers in wich I want the values I have saved in the temp table.
How do I get the values from the table in my report headers? During a report_load() event?
Private Sub Report_Open(Cancel as Integer)
Dim db as Database
Dim rec as Recordset
Set db = CurrentDb
Set rec = db.OpenRecordset("tblTempProjectGegevens")
Me.Project.Value = rec("Project")
Etc...
End Sub

Preserving Single Quotes in Access

I have created a form in Access 2010 that is used to insert data into an existing table. The table contains a Keywords field, Source combo box, and a Code text box where i write the data to be inserted and there is a button for executing the query. The code for the form is:
Private Sub cmd_go_Click()
Dim insertstring As String
insertstring = "INSERT INTO KWTable (KW, Source, Code) VALUES('" & text_key.Value & "','" & combo_source.Value & "','" & txt_code.Value & "');"
DoCmd.RunSQL insertstring
End Sub
The code is simple, it inputs the data to the table so i can reference it for future use. Now the problem I am having is that when I try to add long bits of code that I use in SQL Server i get a syntax missing expression error which I am assuming is coming from the single quotes since the code is from SQL. I am getting the error because when i am trying to store a code i used in SQL Server it uses single quotes which access does not recognise. I think if I try to write in the code for the insert form something to help convert the single quotes into double quotes, then reconvert them back to single quoteswill help solve the problem. I just cant figure out how to do it and could really use some help.
Thank You
You can avoid trouble with included quotes in your inserted text by using a parameter query.
Consider an approach such as this for cmd_go_Click().
Dim strInsert As String
Dim db As DAO.database
Dim qdf As DAO.QueryDef
strInsert = "PARAMETERS pKW TEXT(255), pSource TEXT(255), pCode TEXT(255);" & vbCrLf & _
"INSERT INTO KWTable (KW, Source, Code) VALUES (pKW, pSource, pCode);"
'Debug.Print strInsert
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strInsert)
qdf.Parameters("pKW") = Me.text_key.value
qdf.Parameters("pSource") = Me.combo_source.value
qdf.Parameters("pCode") = Me.txt_code.value
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
However, I don't understand how JoinCells() fits in.
I use a function that handles Null Values, and escapes single quotes (by converting them to two single quotes) when creating SQL statements directly:
Function SafeSQL(ByVal pvarSQL As Variant) As String
SafeSQL2 = Replace(Nz(pvarSQL, ""), "'", "''")
End Function
Then in your routine you would have:
insertstring = "INSERT INTO KWTable (KW, Source, Code) VALUES('" & SafeSQL(text_key.Value) & "','" & SafeSQL(combo_source.Value) & "','" & SafeSQL(txt_code.Value) & "');"

saving data from form to table in access

I have a form, and I want to fill it, and then save some of the fields into an existing table called Order.
I'm trying to do this with this line of code:
CurrentDb.Execute "INSERT INTO Order (OrderNumber)" & " VALUES (' " & Me.order & " ')"
I have also tried it like this
CurrentDb.Execute "INSERT INTO Order (OrderNumber)" & " VALUES ( " & Me.order & " )"
but it doesn't seem to make a difference. I keep getting the following error:
run-time error '3134': syntax error in INSERT INTO statement.
what am I doing wrong?
Order is a reserved word. If you must keep that as the table name, bracket it to avoid confusing the db engine.
Dim strInsert As String
strInsert = "INSERT INTO [Order] (OrderNumber) VALUES ('" & Me.order & "')"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailOnError
If OrderNumber is numeric data type instead of text, discard those single quotes from the INSERT statement.
Store your statement in a string variable. Then use Debug.Print to examine the completed statement you're asking the engine to execute. You can view the Debug.Print output in the Immediate window. Go there with Ctrl+g Copy the statement and paste it into SQL View of a new Access query for troubleshooting.