简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM