Insert into statement with an apostophe using VBA? - sql

I have a form with textboxes. I am inserting what the user enters into the textbox into a table. If the user enters an apostrophe in the textbox labeled "Me.ProjectName", I get an error. My code is:
CurrentDb.Execute "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Me.ProjectName & "')"

You should not construct and execute dynamic SQL based on user input. You should use a parameterized query, something like:
Dim cdb As DAO.Database
Set cdb = CurrentDb
Dim qdf As DAO.QueryDef
Set qdf = cdb.CreateQueryDef("", _
"INSERT INTO Table1 (ProjectNumber, Title) VALUES (#prjnum, #title)")
qdf.Parameters("#prjnum").Value = ProjectNumber
qdf.Parameters("#title").Value = me.ProjectName
qdf.Execute

You should escape your strings possibly containing quotes by replacing a quote with 2 quotes:
Dim SQL As String
SQL = "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Replace(Me.ProjectName, "'", "''") & "')"
CurrentDb.Execute SQL

Related

Insert Date into MS Access vba Query

I'm trying to insert the current date into a table using VBA in MS Acess. The date gets inserted as 12/30/1899 No matter what I try. Any advise to fix this? Here is my code
Dim StrSQL As String
Dim db As Database
Dim InID As Integer
Dim Inputcasedate As String
Dim InputCaseType_Id As Integer
InID = Me.PgmPart_ID
Inputcasedate = Date
InputCaseType_Id = 1
StrSQL = "INSERT INTO CaseNotes (PgmPart_ID,CaseType_ID,CaseDate) " & _
"VALUES (" & InID & "," & InputCaseType_Id & "," & Inputcasedate & ")"
In MS Access, literal date values must be delimited by pound/numeral/hashtag symbols: #.
StrSQL = "INSERT INTO CaseNotes (PgmPart_ID,CaseType_ID,CaseDate) " & _
"VALUES (" & InID & ", " & InputCaseType_Id & ", #" & Inputcasedate & "#)"
However, like VBA, Access SQL maintains the Date() function. So use this expression inside the SQL statement and avoid the concatenated VBA variable.
StrSQL = "INSERT INTO CaseNotes (PgmPart_ID,CaseType_ID,CaseDate) " & _
"VALUES (" & InID & ", " & InputCaseType_Id & ", Date())"
However, consider the industry best practice with parameterized SQL which MS Access's DAO supports via QueryDefs.Parameters. Doing so, requires no value delimiters like quotes for strings or numerals for dates and aligns data types between app layer (VBA) and database.
Dim StrSQL As String
Dim db As Database
Dim qdef As QueryDef
' PREPARED STATEMENT (NO VBA VARIABLES)
StrSQL = "PARAMETERS ParamInID Long, ParamInputCaseType_Id Long; " & _
"INSERT INTO CaseNotes (PgmPart_ID, CaseType_ID, CaseDate) " & _
"VALUES (ParamInID, ParamInputCaseType_Id, Date());"
' INITIALIZE DAO OBJECTS
Set db = CurrentDb
qdef = db.CreateQueryDef("", StrSQL)
' BIND PARAMETERS
qdef!ParamInID = Me.PgmPart_ID
qdef!ParamInputCaseType_Id = 1
' EXECUTE ACTION
qdef.Execute
Set qdef = Nothing: Set db = Nothing

Is it the same to insert into tables from query as from table using VBA?

so this is my code below it works just fine when selecting from a table :
Private Sub cmdStart_Click()
Dim strSql1 As String
Dim strSql2 As String
Dim strSql3 As String
Dim strSql4 As String
Dim qdef As DAO.QueryDef
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Set dbs = CurrentDb
strSql1 = "insert into qoyod_details (qaed_num,f_year,qaed_date,l_value,Hesab_code) " & _
"select " & Forms("qoyod").qaed_num & " , " & Forms("qoyod").f_year & " , format('" & Forms("qoyod").qaed_date & "' , 'dd/mm/yyyy') , sum(sale_bill_total), 167 " & _
"from sale_bill where sale_bill_date between format( '" & Me.cmbQFrom & "' ,'mm/dd/yyyy') and format( '" & Me.cmbQTo & "' ,'mm/dd/yyyy') and sale_bill_type = 1 "
dbs.Execute strSql1
but when I try to select from a query it just wont work
is there something am doing wrong ?
Thanks in advance.
First you'll need to enclose your data correctly:
numbers need no enclosure: 200
string need to be enclosed with ' or ": 'String' or "String"
Dates need to be enclosed with #: #2020-11-22#
When concatenating strings to an SQL string I usually use the single quotes '
So just guessing on what the field data types are, here is what you SQL string should look like:
strSql1 = "insert into qoyod_details (qaed_num,f_year,qaed_date,l_value,Hesab_code) " & _
"select " & Forms("qoyod").qaed_num & " , " & Forms("qoyod").f_year & " , #" & format(Forms("qoyod").qaed_date, "yyyy-mm-dd") & "#, sum(sale_bill_total) , 167 " & _
"from sale_bill where sale_bill_date between #" & format( Me.cmbQFrom, "yyyy-mm-dd") & "# and #" & format(Me.cmbQTo, "yyyy-mm-dd") & "# and sale_bill_type = 1"
dbs.Execute strSql1
To simplify date conversion use the ISO format yyyy-mm-dd, this will prevent any accidental switching between the day and month in certain configurations.
If you're still getting an error, then try printing the result to the Immediate Window like this for troubleshooting:
Debug.Print strSql1
dbs.Execute strSql1
before trying to execute the string.

I do not see the results of the VBA code in access

I have written a VBA code in Access. But, a table or a query does not added to the access. I do not see the results of the VBA code in access.
Option Compare Database
Sub TransformX1()
Dim strSQL As String
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Set dbs = CurrentDb
strSQL = ""
strSQL = strSQL & "TRANSFORM Sum(BAR1.[TON]) AS SumOfTON " & vbCrLf
strSQL = strSQL & "SELECT BAR1.[MABD], Sum(BAR1.[TON]) AS [Total Of TON] " & vbCrLf
strSQL = strSQL & "FROM BAR1 " & vbCrLf
strSQL = strSQL & "WHERE (((BAR1.[MABD])<1300) AND ((BAR1.[MAGH])<1300) AND ((BAR1.G)=1)) " & vbCrLf
strSQL = strSQL & "GROUP BY BAR1.[MABD] " & vbCrLf
strSQL = strSQL & "PIVOT BAR1.[MAGH];"
Set rst = dbs.OpenRecordset(strSQL)
End Sub
Since your SQL is static, there is no reason to (re)create it in VBA.
Create a query and paste your SQL into this. This will be a crosstab query.
Save it using a name, say, Q1.
Now, create a new query, say Q2, where you use Q1 as source. Adjust query Q2 to be either an append query or a create table query. This query you can run (execute) at any time.

Formatting Field In Dao Database - Access VBA

I have this code for a DAO - Database
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim sqlinsert As String
sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Number]) Values ('" & rs("[Number]") & "') "
DoCmd.RunSQL (sqlinsert)
When I run this, the Number will often be to a large decimal place, implying the need for Round(,2) or Format(, " #.00").
However, this code does not function.
sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Number]) Values ('" & rs("Format([Number], "#.00")") & "') "
Any ideas as to what the code should be?
sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Number]) Values ('" & Format(rs("[Number]"), "#.00") & "') "

How can I insert data from an Access form into a sql table using VBA?

Here is what I have, I'm trying to take fields from an Access form (data comes from one linked sql table) and insert them into another linked sql table:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", " Me.email & ")
DoCmd.RunSQL StrSQL
But I am getting this error
Compile error: Sub or Function not defined
I think you are just missing some double quotes:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
"VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", """ & Me.email & """)"
DoCmd.RunSQL StrSQL
You can try to print the contents of StrSQL and check the query before running it:
Debug.Print StrSQL
but I prefer not to create SQL strings with concatenated values (what happens if Me.StravellerUFID contains a double quote?)
I would suggest you to insert data using DAO:
Dim rs as Recordset
Set rs = CurrentDb.OpenRecordset("dbo_Expense_Projection")
rs.AddNew
rs!StatusID = Me.StatusID
rs!TravellerUFID = Me.TravellerUFID
' ...other fields
rs.Update
rs.Close
There are also some ampersands missing in the SQL-String:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
"VALUES(" & Me!StatusID & ", " & Me!TravellerUFID & ", " & Me!SubmitterUFID & ", """ & Me!email & """)"
And I think you should use exclamation mark between "Me" and fieldname. But I do not want to argue with the experts here about that... ;)
Here is what ended up working:
Dim StrSQL As String
StrSQL = "INSERT INTO dbo_Expense_Projection (StatusID,TravellerUFID,Email)
VALUES('" & Form!StatusID & "','" & Form!TravellerUFID & "','" & Form!Email & "')"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True