This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Excel VBA INSERT INTO statement using variables
I've just started learning a bit of VBA, I've managed to import data from a DB created in SQL Server just fine, now I'm trying to export data from Excel into the same DB.
The following works just fine:
Dim cnState As ADODB.Connection
Dim sSQL As String
Set cnState = New Connection
With cnState
.Provider = "SQLOLEDB"
.ConnectionString = "server=.\SQLEXPRESS; Trusted_Connection=Yes; database=SIM_PROJ"
.Open
End With
sSQL = "Insert Into Alunos Values ('3', 'Tiago Aleixo', 'Rua dos Pincéis' , '1990-05-26' , 'M' , 'Multimédia' , 'D')"
cnState.Execute sSQL
End Sub
Private Sub btn_goMenu_Click()
Sheet1.Select
The only issue is, I've only managed to figure out how to insert actual values through the code, I want to be able to read a whole line in Excel and insert it into my DB.
Something like this:
sSQL = "Insert Into Alunos Values (Range(A4).Value, Range(B4).Value, Range(C4).Value, Range(D4).Value, Range(E4).Value, Range(F4).Value, Range(G4).Value)"
IE, I only want values from line 4 to be inserted.
Probably you have to build the string more incrementally like:
SQL = "INSERT INTO alunos VALUES ('" + Range(A4).Value + "', '" + Range(A5).Value + "', '"...
The syntax you show looks ilke it would try to insert the string "Range(A4).Value" into the database.
Save your file as comma delimited CSV file and then you can use bulk insert as below.
declare #sql varchar(max)
set #sql = "BULK INSERT Alunos FROM '"+#File+"' WITH (FIELDTERMINATOR = ',') "
exec (#sql)
Related
I'm using MS Access 2013. My current issue is with the following code, I use to log user activity.
Table is called: tbl-activitylog and has five columns :
id
timestamps
Username
Activity
Additional
I checked code many times char after char and don't know what's wrong :(
TempVars("UserName").Value = "admin"
Logging("Logon", "system")
Public Sub Logging(Activity, Additional As String)
Dim sql_code As String
sql_code = "INSERT INTO tbl-activitylog(Username, Activity, Additional) VALUES('" & TempVars("UserName").Value & "','" & Activity & "','" & Additional & "')"
Debug.Print sql_code
CurrentDb.Execute sql_code
End Sub
Debug print shows:
INSERT INTO tbl-activitylog(Username, Activity, Additional) VALUES('admin','Logon','System')
Becaus of using "-" you have to do it in this way [tbl-activitylog]
sql_code = "INSERT INTO [tbl-activitylog](Username, Activity, Additional) VALUES('" & TempVars("UserName").Value & "','" & Activity & "','" & Additional & "')"
This 3134 error denotes a syntax error in your INSERT statement. As the name of your table contains a dash, you need to enclose it between brackets :
INSERT INTO [tbl-activitylog]
(Username, Activity, Additional)
VALUES('admin','Logon','System')
Generally speaking you may as well enclose all fields and table names, to avoid all risks of clashes with ms-access reserved words, like :
INSERT INTO [tbl-activitylog]
([Username], [Activity], [Additional])
VALUES('admin','Logon','System')
Consider a parameterized query, an industry best practice in any application layer language running SQL in any database. With QueryDefs, you can parameterize queries in MS Access.
Even more MS Access will not allow you to save queries with syntax issues. So, be sure to escape special characters and reserved words with square brackets or backticks.
SQL (save below as a query object)
PARAMETERS UsernameParam Text, ActivityParam Text, AdditionalParam Text;
INSERT INTO [tbl-activitylog] ([Username], [Activity], [Additional])
VALUES ([UsernameParam], [ActivityParam], [AdditionalParam])
VBA (reference above query and bind values without quotes or concatenation)
TempVars("UserName").Value = "admin"
Logging("Logon", "system")
Public Sub Logging(Activity, Additional As String)
Dim sql_code As String
Dim qdef As QueryDef
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
' BIND PARAMS
qdef![UsernameParam] = TempVars("UserName")
qdef![ActivityParam] = Activity
qdef![AdditionalParam] = Additional
qdef.Execute dbFailOnError
Set qdef = Nothing
End Sub
This question already has answers here:
How do I use parameters in VBA in the different contexts in Microsoft Access?
(2 answers)
Closed 4 years ago.
I'm trying to pass values from a Form into my database, via SQL:
Private Sub Befehl4_Click()
Dim SQL As String
Dim unique As String
unique = Forms!frm_test!PN
SQL = "INSERT INTO tab_test (Feld1) VALUES (unique)"
DoCmd.RunSQL SQL
End Sub
When I execute this code from my button in my Form, unique isn't passed to the SQL-command. I have to type it in. When writing the SQL-command this way:
SQL = "INSERT INTO tab_test (Feld1) VALUES (Forms!frm_test!PN)"
It works how expected.
What am I missing or doing wrong?
SQL = "INSERT INTO tab_test (Feld1) VALUES ('" & Forms!frm_test!PN & "')"
I am using VBA in Excel to generate an INSERT statement to be executed within the VBA procedure. When I run the code, I get the runtime error 'Syntax error in INSERT INTO statement' when I get to the Execute statement - the same useful message you get if you have done something wrong in the SQL view within Access. However, when I run the SQL string generated by the VBA code in Access, using old fashioned Copy & Paste, it runs fine - no error message, and the records are there when I open the table.
It is not the way I am executing the command in VBA either as I have a DELETE statement that works as it should do. Code works as below:
Set Cn = CreateObject("ADODB.Connection")
Set Rs = CreateObject("ADODB.Recordset")
Cn.Open cnPath
SQLStr = "SELECT * FROM [" & tblName & "]"
Rs.Open SQLStr, Cn, 1, 3
'code builds SQL str here by looping through
'table headers and relevant row
Cn.Execute SQLStr
Resulting SQLStr is something like this:
INSERT INTO [Size Profiles] (Season,Region,Department,ProfType,ColourID,ArticleNumber,StyleName,Colour,Comments,Channel,Fit,SizeProfile,LastChanged,Identifier,FileName,Size,RegionSizeRun,Site,ActualSizeProfile,ActualFileName,ActualLastChanged,ActualPairs,Fixing,Oddity) VALUES ('AW2018', 'UK', 'Childrens', '', 188473, 26145715, 'Product Name', 'Product Colour', '', 'Retail', 'F(M)', 0.186, #05/09/2018#, '26145715AW2018DC01UKF(M)', 'New Sizing Template.xlsb', 70, '', 'DC01', 0, '', #05/09/2018#, 0, '0', '')
Has anyone seen this problem before?
Gave up with this after a long day, and sure enough after sleeping on it and looking back at it in the morning I've realised that one of the column names (Size) is a reserved word in MS Access. Pasting the SQL into the design view of Access, the program must do something to fix this this without informing you.
I resolved the issue by adding a piece of code that adds square brackets around the field names, along the lines of:
insertPart1 = "INSERT INTO [" & tblName & "] ("
For c = 1 To maxC
insertPart1 = insertPart1 & "[" & .Cells(1, c).Value & "],"
Next c
insertPart1 = Left(insertPart1, Len(insertPart1) - 1) & ") VALUES "
I've started to use access recently. I am trying to insert a few rows into the database; however, I am stuck as it is throwing an error:
Too few parameters.
I have a table test with only one column in it named start_date I want to insert all the dates between two dates for example if I consider 1/7/2014 to 3/7/2014 I need dates as 1/7/2014,2/7/2014,3/7/2014 in my table, but I have problem inserting the code I used is as follows
Private Sub createRec_Click()
Dim StrSQL As String
Dim InDate As Date
Dim DatDiff As Integer
Dim db As database
InDate=Me.FromDateTxt
'here I have used a code to find out the difference between two dates that i've not written
For i = 1 To DatDiff
StrSQL = "INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );"
StrSQL = StrSQL & "SELECT 'Test'"
db.Execute StrSQL
db.close
i=i+1
next i
End Sub
My code throws an error in the line Db.Execuite StrSQL
as too few parameters.
since you mentioned you are quite new to access, i had to invite you to first remove the errors in the code (the incomplete for loop and the SQL statement). Otherwise, you surely need the for loop to insert dates in a certain range.
Now, please use the code below to insert the date values into your table. I have tested the code and it works. You can try it too. After that, add your for loop to suit your scenario
Dim StrSQL As String
Dim InDate As Date
Dim DatDiff As Integer
InDate = Me.FromDateTxt
StrSQL = "INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
You can't run two SQL statements into one like you are doing.
You can't "execute" a select query.
db is an object and you haven't set it to anything: (e.g. set db = currentdb)
In VBA integer types can hold up to max of 32767 - I would be tempted to use Long.
You might want to be a bit more specific about the date you are inserting:
INSERT INTO Test (Start_Date) VALUES ('#" & format(InDate, "mm/dd/yyyy") & "#' );"
Remove this line of code: For i = 1 To DatDiff. A For loop must have the word NEXT
Also, remove this line of code: StrSQL = StrSQL & "SELECT 'Test'" because its making Access look at your final SQL statement like this:
INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );SELECT 'Test'
Notice the semicolon in the middle of the SQL statement (should always be at the end. its by the way not required. you can also omit it). also, there is no space between the semicolon and the key word SELECT
in summary:
remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #
PROBLEM
I want to insert the current recordset row into a MS Access table. I am currently getting this error
Syntax error (missing operator) in query expression 'rs[columnname]'
CODE
Here is my current code, I am trying to grab all the columns and insert them into a new table.
DoCmd.RunSQL "INSERT INTO tblSummary_Appl_Usage_score VALUES (rs[Configuration], rs[User Input / Output])"
I am not quite sure what i am missing.
Open tblSummary_Appl_Usage_score as a DAO recordset. Then use its .AddNew method to create a new row and store the values from your ADO recordset.
Dim db As DAO.database
Dim rsDao As DAO.Recordset
Set db = CurrentDb
Set rsDao = db.OpenRecordset("tblSummary_Appl_Usage_score", dbOpenTable, dbAppendOnly)
rsDao.AddNew
rsDao![Configuration] = rs![Configuration]
rsDao![User Input / Output] = rs![User Input / Output]
rsDao.Update
With this approach, your code needn't be adapted differently based on the recordset field data types. It will work correctly regardless of data type as long as the matching fields are both the same or compatible data types.
If the type fields in your table tblSummary_Appl_Usage_score are numbers, use this:
DoCmd.RunSQL "INSERT INTO tblSummary_Appl_Usage_score VALUES (" & rs![Configuration] & "," & rs![User Input / Output] & ")"
If the type is string, use this:
DoCmd.RunSQL "INSERT INTO tblSummary_Appl_Usage_score VALUES (""" & rs![Configuration] & """,""" & rs![User Input / Output] & """)"