Having trouble comparing dates Access - vba

I'm new to Access and i'm having trouble with comparing dates in my SQL Query. I can't seem to work around this problem. It works fine if it just input a date like this:
Dim SendTo as string, strSQL as string
DateF = Me.txtDate.value
strSQL = "UPDATE [" & Team & "] SET [" & Init & "] = '" & SendTo & "' WHERE Date = #2020-01-06#;"
I want the date to be a variable set by a textbox on a userform, like this:
strSQL = "UPDATE [" & Team & "] SET [" & Init & "] = '" & SendTo & "' WHERE Date = DateF"
DoCmd.RunSQL strSQL
When i do this, a pop-up box show "Enter parameter value"

Related

How do I limit my sql to an end date in my Access report?

I created an Access database to track work orders and create/print schedules.
On the report I have two different print buttons. One prints the weeks schedule I'm currently viewing to my printer and the other button prints the current week and all future weeks to a PDF. My code for the 2nd button changes the SQL data source and works perfect.
That code looks like this (see pic):
Working SQL code
-----Set default printer to PDF-----
-working code-
-----Set the datasource to show everything from this week and future weeks excluding unscheduled (NULL)-----
Dim strSQL As String
Dim vbDblQuote As String
'set variable to = "
vbDblQuote = Chr(34)
'SQL for the data source
strSQL = "SELECT tblSchedule.ScheduleID, tblSchedule.Scheduled, tblSchedule.Attending, "
strSQL = strSQL & "tblSchedule.Time, tblSchedule.Account, tblSchedule.Address , "
strSQL = strSQL & "tblSchedule.Comments, tblSchedule.Contact, tblSchedule.WONumber "
strSQL = strSQL & "FROM tblSchedule "
strSQL = strSQL & "WHERE (((DatePart(" & vbDblQuote & "ww" & vbDblQuote & ",[Scheduled])) "
strSQL = strSQL & ">=DatePart(" & vbDblQuote & "ww" & vbDblQuote & ",Date()))"
strSQL = strSQL & "AND ((Year([Scheduled]))>=Year(Date())))"
strSQL = strSQL & "ORDER BY tblSchedule.Scheduled, tblSchedule.Attending, tblSchedule.Time;"
'set data source for the report
Reports![rptSchedule].Report.RecordSource = strSQL
-----Print and restore default printer-----
-working code-
Now I want to enable the user to select an end date for the report. I changed the code every which way I could but can't get it to work now. Can anyone help me with the new SQL? It contains a variable to accept the users date.
The new code looks like this (see pic): New Code
-----Set default printer to PDF-----
-working code-
-----Get the end date from user-----
Dim endDate
endDate = InputBox("Select an End Date m/d/yy")
-----Set the datasource to show everything from this week and future weeks excluding unscheduled (NULL)-----
Dim strSQL As String
Dim vbDblQuote As String
'set variable to = "
vbDblQuote = Chr(34)
Dim mySQLVariable
'set variable to user’s end date
mySQLVariable = endDate
'SQL for the data source
strSQL = "SELECT tblSchedule.ScheduleID, tblSchedule.Scheduled, tblSchedule.Attending, "
strSQL = strSQL & "tblSchedule.Time, tblSchedule.Account, tblSchedule.Address , "
strSQL = strSQL & "tblSchedule.Comments, tblSchedule.Contact, tblSchedule.WONumber "
strSQL = strSQL & "FROM tblSchedule "
strSQL = strSQL & "WHERE (((DatePart(" & vbDblQuote & "ww" & vbDblQuote & ",[Scheduled])) "
strSQL = strSQL & ">=DatePart(" & vbDblQuote & "ww" & vbDblQuote & ",Date()))"
strSQL = strSQL & "AND ((Year([Scheduled]))>=Year(Date())))"
strSQL = strSQL & "OR (((DatePart(" & vbDblQuote & "ww" & vbDblQuote & ", [Scheduled])) "
strSQL = strSQL & "<= DatePart(" & vbDblQuote & "ww" & vbDblQuote & ", Date() + '" & (mySQLVariable) & "')) "
strSQL = strSQL & "And ((Year([Scheduled])) = Year(Date() + '" & (mySQLVariable) & "'))) "
strSQL = strSQL & "ORDER BY tblSchedule.Scheduled, tblSchedule.Attending, tblSchedule.Time;"
'set data source for the report
Reports![Reset_Schedule].Report.RecordSource = strSQL
-----Print and restore default printer-----
-working code-
I hope this is clear enough to understand my problem.

Trying to update table in ms Access using VBA but getting failed , used multiple option but table not getting updated

Trying to update table in ms Access using VBA but getting failed , used multiple option but table not getting updated
Dim bod As Date
Dim assets As String
Dim emname As String
Dim ecode As String
Dim Astatus As String
Astatus = "SOLD"
msaved = True
DoCmd.SetWarnings False
bod = Me.datetime.Caption
price1k = Me.cmbox1_1AID.Value
emname = Me.empname.Value
ecod = Nz(Me.code.Value, 0)
//tried using this but not getting updated no error
DoCmd.RunSQL "UPDATE [Asset E7450 List] SET Code = '" & ecod & "',[Date & Time] ='" & bod & "' ,Status ='" & Astatus & "',[Sold To] ='" & empname & "', where Asset-ID ='" & price1k & "'"
// Tried using this no update no error
CurrentDb.Execute "UPDATE [Asset E7450 List] SET Code = '" & ecod & "',[Date & Time] ='" & bod & "' ,Status ='" & Astatus & "',[Sold To] ='" & empname & "', where Asset-ID ='" & price1k & "'"
// Tried this method no data update no error
Dim strSQL As String
strSQL = "UPDATE [Asset E7450 List] SET Code = '" & ecod & "',[Date & Time] ='" & bod & "' ,Status ='" & Astatus & "',[Sold To] ='" & empname & "', where Asset-ID ='" & price1k & "'"
DoCmd.RunSQL strSQL
MsgBox " Booking Request Accepted ", vbInformation
If [Date & Time] is a date/time type field, use # delimiter instead of '. If field is a number type, don't use any delimiter.
Remove the comma in front of WHERE clause.
Need [ ] around Asset-ID field name because of the hyphen.
Advise not to use spaces nor punctuation/special characters in naming convention.

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.

Increase speed of multiple inserts into Access DB from VBA Dictionary

I am attempting to take a VBA Dictionary and either:
Insert a new row into the database if it does not exist
Update the row if it does
While my current code works for this, it runs extremely slowly for the thousands of records I may need to update, and other solutions I have found on this site do not really achieve what I am after. Could anyone help me achieve this? My code so far is below:
Sub UpdateDatabase(dict As Object)
Dim Conn As Object, StrSQL As String, Rs As Object
Dim hmm As ADODB.Recordset
Set Conn = CreateObject("ADODB.Connection")
Conn.Provider = "Microsoft.ACE.OLEDB.12.0"
Conn.Open "C:\XXXX\cfrv2.accdb"
dictCount = dict.Count
counter = 0
For Each varKey In dict.Keys()
Application.StatusBar = Str(counter) & "/" & Str(dictCount)
counter = counter + 1
StrSQL = "SELECT * FROM `All SAMs Backlog` WHERE [LOCID] = '" & varKey & "'"
Set hmm = Conn.Execute(StrSQL)
If hmm.BOF And hmm.EOF Then
StrSQL = "INSERT INTO `ALL SAMs Backlog` ([SAM], [LOCID], [RTC Date], [CFR Status], [CFR Completed Date], [CFR On Hold Reason], [MDU], [ICWB Issue], [Obsolete]) VALUES (dict.Item(varKey)(0), '" & varKey & "', '20/12/2018', '" & dict.Item(varKey)(1) & "', '02/01/2019', '" & dict.Item(varKey)(2) & "' , '" & dict.Item(varKey)(3) & "' , '" &dict.Item(varKey)(4) & "' , '" & dict.Item(varKey)(5) & "')"
Conn.Execute (StrSQL)
Else
'Update the LOC in the table
StrSQL = "UPDATE `All SAMs Backlog` SET ([CFR Status] = '" & dict.Item(varKey)(1) & "', [CFR On Hold Reason] = '" & dict.Item(varKey)(2) & "', [MDU] = '" & dict.Item(varKey)(3) & "', [ICWB Issue] = '" & dict.Item(varKey)(4) & "', [Obsolete] = '" & dict.Item(varKey)(5) & "')"
Conn.Execute (StrSQL)
End If
Next
Conn.Close
End Sub
Any help is appreciated.
Either:
Write the content of the dictionary to a temp table, then run a query as described here:
Update or insert data in table
or:
Open [All SAMs Backlog] as a recordset, loop the dictionary to add or edit records as needed, then close the recordset.

Update SQL MS Access 2010

This is wrecking my brains for 4 hours now,
I have a Table named BreakSked,
and I this button to update the table with the break end time with this sql:
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = " & _
Me.Text412.Value & " WHERE [BreakSked].AgentName = " & Me.List423.Value _
& " AND [BreakSked].ShiftStatus = '1'"
CurrentDB.Execute strSQL1
Text412 holds the current system time and List423 contains the name of the person.
I'm always getting this
"Run-time error 3075: Syntax Error (missing operator) in query
expression '03:00:00 am'
Any help please?
EDIT: Thanks, now my records are updating. But now its adding another record instead of updating the record at hand. I feel so silly since my program only has two buttons and I can't figure out why this is happening.
Private Sub Form_Load()
DoCmd.GoToRecord , , acNewRec
End Sub
Private Sub Command536_Click()
strSQL1 = "UPDATE BreakSked SET BreakSked.EndTime = '" & Me.Text412.Value & "',BreakSked.Duration = '" & durationz & "' " & vbCrLf & _
"WHERE (([BreakSked].[AgentID]='" & Me.List423.Value & "'));"
CurrentDb.Execute strSQL1
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
Private Sub Command520_Click()
strSql = "INSERT INTO BreakSked (ShiftDate,AgentID,StartTime,Status) VALUES ('" & Me.Text373.Value & "', '" & Me.List423.Value & "', '" & Me.Text373.Value & "','" & Me.Page657.Caption & "')"
CurrentDb.Execute strSql
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
You wouldn't need to delimit Date/Time and text values if you use a parameter query.
Dim strUpdate As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
strUpdate = "PARAMETERS pEndTime DateTime, pAgentName Text ( 255 );" & vbCrLf & _
"UPDATE BreakSked AS b SET b.EndTime = [pEndTime]" & vbCrLf & _
"WHERE b.AgentName = [pAgentName] AND b.ShiftStatus = '1';"
Debug.Print strUpdate ' <- inspect this in Immediate window ...
' Ctrl+g will take you there
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strUpdate)
qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pAgentName").Value = Me.List423.Value
qdf.Execute dbFailOnError
And if you always want to put the current system time into EndTime, you can use the Time() function instead of pulling it from a text box.
'qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pEndTime").Value = Time() ' or Now() if you want date and time
However, if that is the case, you could just hard-code the function name into the SQL and dispense with one parameter.
"UPDATE BreakSked AS b SET b.EndTime = Time()" & vbCrLf & _
As I said in my comment you need to wrap date fields in "#" and string fields in escaped double quotes
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = #" & _
Me.Text412.Value & "# WHERE [BreakSked].AgentName = """ & Me.List423.Value & _
""" AND [BreakSked].ShiftStatus = '1'"