I am trying something that has been done hundreds of times - except my code does not compile. Using this as a reference How to do INSERT into a table records extracted from another table I came up with the following sub, that is supposed to clear a table and refill it from another linked table (The idea is to liberate the linked table so it doesn't have a .laccdg file in its name for long)
Private Sub Form_Open(Cancel As Integer)
Dim rsDocs As Recordset
Dim sqlQuery As String
DoCmd.RunSQL "DELETE * FROM [Docs]"
sqlQuery = "INSERT INTO [Docs] (Numero, Description, [ID Symix], Groupe, [ID Sami])" & _
" SELECT [Unité] & "" "" & [Numéro Document] AS Numero, Description, [ID Symix], [Groupe Source], [ID Doc Sami]" & _
" FROM [Documents]"
Debug.Print sqlQuery
Set rsDocs = CurrentDb.OpenRecordset(sqlQuery)
CurrentDb.Execute sqlQuery
rsDocs.Close
Set rsDocs = Nothing
End Sub
I get an error on the execute line. The sql statement is wrong. Can someone see where it falters? Is the use of "" "" to join two fields together acceptable in this situation?
Also, clearing the table prompts a message asking if i am sure i want to do this. Will setting DisplayAlerts to False have negative consequences? Or should it be harmless if I put it back to True right after?
A general hint for debugging queries you design in VBA:
Do a Debug.Print of the SQL (you already have that)
Create a new query, close "Add tables"
switch to SQL view and paste your sql from the debug window
either execute the sql, or switch to design view.
Usually you will get a more specific error message from the query editor than what you get from VBA.
DisplayAlerts in Access is: DoCmd.SetWarnings True/False
But it is better to avoid it by using DB.Execute instead of DoCmd.RunSQL
No need for extra set of double quotes
"INSERT INTO [Docs] (Numero, Description, [ID Symix], Groupe, [ID Sami])" & _
" SELECT [Unité] & " " & [Numéro Document] AS Numero, Description, [ID Symix], [Groupe Source], [ID Doc Sami]" & _
" FROM [Documents]"
Instead of 2 sets of double quotes, which didn't work, or 1 set of double quotes, which don't produce a valid string, use 1 set of single quotes:
sqlQuery = "INSERT INTO [Docs] (Numero, Description, [ID Symix], Groupe, [ID Sami])" & _
" SELECT [Unité] & ' ' & [Numéro Document] AS Numero, Description, [ID Symix], [Groupe Source], [ID Doc Sami]" & _
" FROM [Documents]"
Related
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.
I know, there are lots of answers out there for this problem which should be trivial, but I did not find the right one. Here is my problem:
I open a record set with the following select statement:
SELECT twinecellar.produktnavn, twinecellar.land,
twinecellar.produkttype, twinecellar.år,
twinecellar.antall, twinecellar.poeng,
twinecellar.Picture, twinecellar.KR,
twinecellar.Poengsum, twinecellar.Sum
FROM twinecellar
WHERE (((twinecellar.land)=forms!fmainview!list13)
And ((twinecellar.produkttype)=forms!fmainview!list15))
ORDER BY twinecellar.poeng;
In the immidiate window I see that list 13 contains "france" and list 15 contains "red"
When I create a new Query with this statement, it's working, however, on the rst.Open gsStrQuery I get this error. gsStrQuery contains the select string.
Here is the code:
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Set conn = CurrentProject.Connection
Set rst = New ADODB.Recordset
rst.CursorType = adOpenDynamic
rst.ActiveConnection = conn
rst.Open gsStrQuery
Anybody out there with a good idea about this issue?
When you build your SQL string, concatenate the "parameters" values into the string.
gsStrQuery = "SELECT twinecellar.produktnavn, twinecellar.land, " & _
"twinecellar.produkttype, twinecellar.år, " & _
"twinecellar.antall, twinecellar.poeng, " & _
"twinecellar.Picture, twinecellar.KR, " & _
"twinecellar.Poengsum, twinecellar.Sum " & _
"FROM twinecellar " & _
"WHERE (((twinecellar.land)= '" & forms!fmainview!list13 & "') " & _
"And ((twinecellar.produkttype)= '" & forms!fmainview!list15 & "')) " & _
"ORDER BY twinecellar.poeng;"
That way your parameter values are hard coded into the string before you try to open the query.
(Also note: I added single quotes around your parameters to indicate they are strings.)
(Also also note: & _ is a line continuation for VBA so your SQL string concatenates properly. This allows you have a readable SQL code that's nicely indented.)
________________________________
There is also a way to use your current gsStrQuery and assign parameters values to the ADO recordset. (But I find the above Replacement method much easier to read when going back to review the code. The only drawback is you have to rebuild your SQL string each time your parameters change. But that overhead is minimal for non complicated queries.)
However, if you really want to use ADO parameters, you can find a useful description here.
Hope that helps :)
I am having some trouble formatting an SQL string in Access, I can never seem to debug these syntax issues with SQL strings. I have this string:
strSQL = "SELECT * FROM FXData WHERE ShortCode=" & Forms!FXVolatility.cboCurve.Value & " AND MaxOfMarkAsOfDate=#" & MaxOfMarkAsofDate & "# ORDER BY MaxOfMarkAsOfDate "
debug.print strSQL
Set rs = CurrentDb.OpenRecordset(strSQL, Type:=dbOpenDynaset, Options:=dbSeeChanges)
which prints
SELECT * FROM FXData WHERE ShortCode=USD.XS AND MaxOfMarkAsOfDate=#3/31/2016# ORDER BY MaxOfMarkAsOfDate
However this gives me a "Too Few Parameters, expected 1" error.
All the fields and their associated values that are referenced in strSQL exist in the referenced table. What could the error be?
Also if you've got any resources on how to debug/identify these specific access SQL formatting issues I'd be happy to hear them.
In SQL, strings need to be put in single or double quotes. Thus, your output should look like this:
... WHERE ShortCode='USD.XS' ...
Thus, your code becomes:
strSQL = "SELECT * FROM FXData WHERE ShortCode='" & _
Replace(Forms!FXVolatility.cboCurve.Value, "'", "''") & _
"' AND MaxOfMarkAsOfDate=#" & MaxOfMarkAsofDate & _
"# ORDER BY MaxOfMarkAsOfDate "
The Replace ensures that any single quotes occurring within cboCurve.Value are properly escaped.
Note that it is recommended to use parameters instead of string concatenation to "fill" values into an SQL statement. An example for how to do this in MS Access can be found in the answer to this question:
VBA OpenRecordset Producing Too few parameters. Expected 2. Error
I have been working on creating an extremely simple database with only 4 tables and only a few pieces of information per column. One of my tables is called "Customer" and inside of this table there or 4 columns for information.
I have a button on my "AddCustomerForm" that runs the following command
Private Sub cmdadd_Click()
CurrentDb.Execute "INSERT INTO Customer(Customer ID, Email, Identifier) " & _
= VALUES(Customer ID, Email, Identifier)
End Sub
My Add customer form looks like this:
Could someone please point out what I am messing up? The error I receive is :
Syntax error.
There's a few issues I see - is [Customer ID] an autonumber field? If so don't include it.
Also - if you're running a Manual Insert I assume your form is NOT bound to your table, though I begin to wonder why Customer ID is shown on the form as being editable?
Finally it looks like Location is a numeric ID belonging to ID field of the Location dropdown that fills in the Business ID field
This will help you debug your SQL and show us what's wrong
Add it to your button and show us the value shown in Immediate Window when the code halts
Dim strSQL as string
strSQL = "INSERT INTO Customer ([Customer ID], Email, Identifier) VALUES (" _
& me.[Customer ID] & ",""" & Me.[Email] & """,""" & Me.[Identifier] & """)"
Debug.print strSQL
CurrentDb.Execute strSQL
If Customer ID is AutoNumber try this instead (assuming form is UNBOUND) and Location is ID value of first column of dropdown
Dim strSQL as string
strSQL = "INSERT INTO Customer (Email, Identifier) VALUES (" _
& me.[Customer ID] & ",""" & Me.[Email] & """, & Me.[Identifier] & ")"
Debug.print strSQL
CurrentDb.Execute strSQL
Private Sub cmdadd_Click()
CurrentDb.Execute "INSERT INTO Customer ([Customer ID], Email, Identifier) VALUES([Forms]![MyFormName]![CustomerIDTextboxName], [Forms]![MyFormName]![EmailtextboxName], [Forms]![MyFormName]![IdentifierTextboxName]);"
End Sub
Access requires brackets around any field name with a space. I also deleted the = before VALUES and changed the values to reference your form controls, which you will have to name appropriately. You also need a semi-colon to complete the statement and need to close your double-quotes.
This page might help with syntax.
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.