Insert Date into MS Access vba Query - sql

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

Related

MS. Access - VBA SQL string not returning any records

As part of a larger project I'm trying to copy records from one table to another but I'm stuck on the first step trying to get the records from the 1st table
My strSQL string in VBA is not returning any record's at the .RecordCount but it should be 2
The SQL from the query builder is
SELECT tbl_BOM_Requirments.ID, tbl_BOM_Requirments.PrtNmber_LinkField, tbl_BOM_Requirments.RequiredMaterialPrtNum, tbl_BOM_Requirments.RequiredMaterialDescription FROM tbl_BOM_Requirments WHERE (((tbl_BOM_Requirments.PrtNmber_LinkField)="PRT468"));
That works fine.. PRT468 is the current record - in VBA I'm using a variable PrtNbrGt
Private Sub Command15_Click()
Dim rstSource As DAO.Recordset
Dim rstInsert As DAO.Recordset
Dim fld As DAO.Field
Dim strSQL As String
Dim lngLoop As Long
Dim lngCount As Long
Dim PrtNbrGt As String
PrtNbrGt = Me.SCSPartNumb
strSQL = "SELECT tbl_BOM_Requirments.RequiredMaterialPrtNum" & vbCrLf & _
"FROM tbl_BOM_Requirments" & vbCrLf & _
"WHERE (tbl_BOM_Requirments.PrtNmber_LinkField) = "" & PrtNbrGt"""
Set rstInsert = CurrentDb.OpenRecordset(strSQL)
Set rstSource = rstInsert.Clone
With rstSource
lngCount = .RecordCount
For lngLoop = 1 To lngCount
Has anyone got any suggestions why it's not returning any records?
You need to replace the double quotes in your working SELECT with single quotes as the doubles quotes are in use to delimiter the string
strSQL = "SELECT tbl_BOM_Requirments.RequiredMaterialPrtNum " & vbCrLf & _
"FROM tbl_BOM_Requirments " & vbCrLf & _
"WHERE (tbl_BOM_Requirments.PrtNmber_LinkField) = '" & Replace(PrtNbrGt, "'", "''") & "'"
But your code should have goven you some errors anyway
but you can use parameters see https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/parameters-declaration-microsoft-access-sql
You are tangled up in double quote inception. Instead:
"WHERE (tbl_BOM_Requirments.PrtNmber_LinkField) = """ & PrtNbrGt & """"
You could also do:
"WHERE (tbl_BOM_Requirments.PrtNmber_LinkField) = " & CHR(34) & PrtNbrGt & CHR(34)
That's a little easier to read. CHR(34) that is used in this example is a literal double quote.

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.

Insert into statement with an apostophe using VBA?

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

Copy MS Access table to different MS Access

Please help; I wanted to copy an MS Access table and its data into another table at different MS Access database. I came across hundreds of access databases which has to be reformatted, I decided to write VB.Net code and format one table so that it can be copy to other hundreds instant of formatting one by one.
Here is my trial code:
Dim cmdCreate as New OleDb.OleDbCommand("SELECT * INTO [Hierarchy] IN "c:\hierarchy.pdb" FROM [Hierarchy] WHERE 0=1", con1)
cmdCreate.ExecuteNonQuery
Note: con1 datasource is deference with table2 directory.
here is a function in Access you can put a loop around with appropriate args. The dbSource and dbTarget are the full path names.
Public Function ExportTableToDatabase (TableName As String, dbSource As String, dbTarget As String, Optional Append As Boolean = False) As Boolean
On Error GoTo Error_Trap
Dim SQL As String
Dim db As DAO.Database
Set db = CurrentDb()
If Append Then
'The sql will use APPEND TO TABLE syntax
SQL = "INSERT INTO " & TableName & " IN """ & dbTarget & """ " _
& "SELECT " & TableName & ".* FROM " & TableName & " IN """ & dbSource & """ "
Else
'The sql will use CREATE TABLE syntax
SQL = "SELECT " _
& TableName & ".* INTO " & TableName & " " _
& "IN """ & dbTarget & """ " _
& "FROM " & TableName & " " _
& "IN """ & dbSource & """ "
End If
db.Execute SQL, dbFailOnError + dbSeeChanges
ExportTableToDatabase = True
Cleanup:
set db = nothing
Exit Function
Error_Trap:
msgbox Err.Number, Err.Description
Resume Cleanup
Resume
End Function

data type mismatch error with OpenRecordSet

Using Access 2007. I'm trying to write a VBA function that will construct a query from the table name, fields, and values that I pass as parameters. I keep getting a "Run-time error '3464': Data type mismatch in criteria expression."
Here's the code:
Function getPrimaryFromForeign(db As Database, table As String, field As String, _
value As Long, _
field2 As String, value2 As Long) As Long
Dim sStr As String
Dim istr As String
Dim rs As Recordset
sStr = "select * from " & table & " where " _
& field & "='" & value & "' and " & field2 & "='" & value2 & "'"
istr = "insert into " & table & "(" & _
field & "," & field2 & ") values ('" & value & "','" & value2 & "')"
Set rs = db.OpenRecordset(sStr)
If rs.RecordCount < 1 Then
db.Execute (istr), dbFailOnError
Set rs = db.OpenRecordset(sStr)
End If
getPrimaryFromForeign = rs("id")
End Function
The error occurs at the line:
Set rs = db.OpenRecordset(sStr)
I think it has something to do with the variable types of Value and Value2. But I've checked them using typename(), and they're both Long when OpenRecordSet() is called. The query is on a table where both of those fields are of type Number. So why is there a type mismatch?
This can occur if you have both DAO and an ADO in you reference library.
In this case declaration order in both your Dim statements and in the references window matters.
1) "You must reference and use both DAO and ADO Recordset objects, dimension the objects explicitly as follows:
Dim adoRS As ADODB.Recordset
Dim daoRS As DAO.Recordset"
2) "Make sure that the reference for the DAO object library has a higher priority in the References dialog box, or clear the reference to Microsoft ActiveX Data Objects."
see Here:
https://support.microsoft.com/en-us/help/181542/you-receive-a-type-mismatch-error-when-you-run-the-openrecordset-metho
I haven't used Access in a long time, but I think that the problem is because you're enclosing Value and Value2 in single quotes in your SQL statement, and not enclosing the fields in the WHERE clause in brackets.
Try it like this:
sStr = "select * from " & table & " where [" _
& field & "] = " & value & " and [" & field2 & "] = " & value2
istr = "insert into " & table & "([" & _
field & "], [" & field2 & "]) values (" & value & "," & value2 & ")"