Syntax error in date in expression in Access 2016 - ms-access

I am not very good with Access and I am creating a simple booking database wherein the available times will exclude times that were already booked.
I am following a tutorial and it was already working, then suddenly I am getting the error: Syntax error in date in expression
oRS.FindFirst "[ApptTime] Between #" & i - TimeValue("00:00:05") & _
"# And #" & i + TimeValue("00:00:05") & "#"
where oRS is set as DAO.Recordset and it contains the fields CounselorID, ApptDate, ApptTime
I expect to have a list of available times that do not include the time that have been booked already.

If i is some time of the day, use DateAdd to set the interval:
oRS.FindFirst "[ApptTime] Between DateAdd("s", -5, i) And DateAdd("s", 5, i)

Related

VBA SystemTime - 30 days

I am working on a code from a previous developer. This code has SystemTime set up.
Is there a way to get today date and minus 30 days in this format?
Code Below:
Public Function GetIsoTimestampTest() As String
Dim st As SYSTEMTIME
'Get the local date and time
GetSystemTime st
'Format the result
GetIsoTimestampTest = _
Format$(st.wYear, "0000") & "-" & _
Format$(st.wMonth, "00") & "-" & _
Format$(st.wDay, "00") & "T" & _
Format$(st.wHour, "00") & ":" & _
Format$(st.wMinute, "00") & ":" & _
Format$(st.wSecond, "00") & "Z"
End Function
Build a native date & time, add -30 days, format as a string:
utcInIsoFormat = Format$(DateAdd("d", -30, _
DateSerial(st.wYear, st.wMonth, st.wDay) _
+ TimeSerial(st.wHour, st.wMinute, st.wSecond)), "yyyy-mm-ddThh:nn:ssZ")
SYSTEMTIME appears to be a custom type defined elsewhere in your code. It's not a standard type available in Access VBA. So to use it effectively, you need to find the definition. Also GetSystemTime is also likely a custom function exclusive to your code. Here's a sample definition of a similar type, although it may not be exactly what's implemented in your system: http://custom-designed-databases.com/wordpress/2011/get-milliseconds-or-seconds-from-system-time-with-vba/
That said, System Time would refer to the Windows system time. You also have a native ability in VBA to get time using the Now() function. (https://msdn.microsoft.com/en-us/library/office/gg278671.aspx) This returns a variable with type Date, which is equivalent to a number where the integer represents days and the decimal represents time of day. An example to get 30 days prior to today would be:
Dim lastMonth as Date
Dim formattedDate as String
lastMonth = Now() - 30
formattedDate = Format(lastMonth, "yyyy-mm-ddThh:nn:ssZ")
DateSerial happily accepts a negative day count. Thus:
Public Function IsoDateMinus30() As Date
Dim st As SYSTEMTIME
Dim Result As Date
' Get the local date and time
GetSystemTime st
Result = DateSerial(st.wYear, st.wMonth, st.wDay - 30)
' To include time:
'
' Result = _
' DateSerial(st.wYear, st.wMonth, st.wDay - 30) + _
' TimeSerial(st.wHour, st.wMinute, st.wSecond)
IsoDateMinus30 = Result
End Function

Access VBA getting DateDiff results to work with Update SQL statement

I'm using Access 2007 by itself with no connections to SQLserver or anything for this process.
I want to take the result of a few DateDiff functions and use an Update SQL statement to put them into fields on a table. My table's fields are number fields, and I am under the impression that DateDiff returns a number.
I try this, but I get a data type mismatch error on the first DateDiff (Pause1). I tried taking the quotes off of the fields but then I get a different error (can't find the field '|' referred to in your expression).
Here is my code. It really starts at the comment TIME REPORTING CODE HERE:
Private Sub StopNextButton_Click()
'
GetID = Forms!frm_MainMenu!AssocIDBox
CurRecord = Forms!frm_EC_L1_L2![L#].Value
'
DoCmd.RunSQL "UPDATE tbl_Data SET tbl_Data.[tsEndAll] = Now WHERE tbl_Data.[L#] = " & CurRecord & " AND (tbl_Data.[ECName] Like 'L1*' OR tbl_Data.[ECName] Like 'L2*') "
'
'TIME REPORTING CODE HERE'
'
Pause1 = DateDiff("s", "[tsPause1]", "[tsResume1]")
Pause2 = DateDiff("s", "[tsPause2]", "[tsResume2]")
ECTime = (DateDiff("s", "[tsECStart]", "[tsUpdated]") - (Pause1 + Pause2))
LTime = DateDiff("s", "[tsStartAll]", "[tsEndAll]")
'
DoCmd.RunSQL "UPDATE tbl_Data SET [ECTime] = " & ECTime & ", [LoanTime] = " & LTime & " WHERE tbl_Data.[L#] = " & CurRecord & " AND (tbl_Data.[ECName] Like 'L1*' OR tbl_Data.[ECName] Like 'L2*') "
'
'END OF TIME REPORTING CODE'
'
DoCmd.GoToRecord , , acNext
'
ETC.
Based off of your comment I assume that those fields are on the record your form is currently 'viewing'. If so you can just refer to them as Me.tsPause1 without [] or quotes. Pretty sure you can also do just tsPause1 but I find Me.tsPause1 makes it more obvious what you are doing.
However I think you are updating the field you are currently viewing and then immediately trying to access those updated fields. I am fairly certain you will need to a Me.Refresh before those fields' new values are accessible. Hopefully someone with more specific experience will correct me if I am wrong. I think something like this should work for you:
Me.Refresh
Pause1 = DateDiff("s", Me.tsPause1, Me.tsResume1)
Pause2 = DateDiff("s", Me.tsPause2, Me.tsResume2)
ECTime = (DateDiff("s", Me.tsECStart, Me.tsUpdated) - (Pause1 + Pause2))
LTime = DateDiff("s", Me.tsStartAll, Me.tsEndAll)

How to use "INSERT INTO" command from Access VBA to Sharepoint

I'm using a MS Access database linked with a Sharepoint Server. MS Access Forms as FrontEnd and Sharepoint Lists as BackEnd.
Today i can see all the informations from the lists using access forms, without problems.
What i need:
I'm trying to insert new registers on the list, using a SQL command: "INSERT INTO..."
if there is another possibility to insert the record in the list, may be useful
What's happening?
When i call the DoCmd.RunSQL(txtsql), i receive a runtime error 3999 saying i'm disconnected from the server.
My code now:
I tried using recordsets, but didn't succeed.
I need to run this SQL many times, changing the string "txtSql" inside a loop. Like this:
Dim MaxSonda As Integer
'Get the max ID from the list
MaxSonda = Nz(DMax("IdSonda", "Sondas", "((Sondas.[Tipo Sonda])<>1 Or (Sondas.[Tipo Sonda]) Is Null)"), 0)
MsgBox "MaxSonda = " & MaxSonda
'Run the code for each "sonda"
Do While MaxSonda > 1
If Nz(DLookup("[Tipo Sonda]", "Sondas", "Sondas!IdSonda = " & MaxSonda), 1) <> 1 Then
DoCmd.OpenTable "Resumo", acViewNormal, acAdd
DoCmd.GoToRecord acDataTable, "Resumo", acNewRec
txtSql = "INSERT INTO Resumo ( Data, Sonda, Status ) SELECT #" & LastData + 1 & "#, " & MaxSonda & ", 0;"
MsgBox txtSql
DoCmd.RunSQL txtSql
DoCmd.Close acTable, "Resumo", acSaveYes
End If
MaxSonda = MaxSonda - 1
Loop
P.S.: The MsgBox is just for check the steps
thanks for help
You don't need to open the list/table to insert a record. I don't know why you are using loop to insert rows but if that is your intention try this SQL_COMMAND within your loop:
If Nz(DLookup("[Tipo Sonda]", "Sondas", "[IdSonda] = " & MaxSonda), 1) <> 1 Then
txtSql = "INSERT INTO Resumo ( Data, Sonda, Status ) VALUES ('" & LastData + 1 & "'," & MaxSonda & ",0);"
MsgBox txtSql
DoCmd.RunSQL txtSql
End If
also note #tags are used to insert dates in Access, if you are intend to save dates save them in international format as strings like
vba.Format$([date_field],"yyyy-mm-dd hh:mm:ss")
this way you can just save as string without using the #tags.
Maybe this could help somebody. I did have the same problem and i solved it removing the sharepoint list from access and add it again. Take a seconds to make a sql query but it works.
greet

Order of records that DLookup uses to return first value (Access VBA)

long time stalker but first time poster here so apologies for any social faux pas I make.
I am trying to use DLookup to search for a record in a table using VBA. The specific record I am after is the one closest in date to sdate (a user specified date) which also meets some other criteria. There are likely to be a couple of records with dates prior to sdate which meet the same criteria, and I am only interested in the one which is chronologically closest to sdate.
The following is a simplified example of the code I am using to try and achieve this. I use baseTestString as there are quite a few similar DLookup expressions so it saves typing and clarifies the code slightly (to me at least).
DoCmd.OpenTable ("Results")
DoCmd.SetOrderBy "[Survey_Date] Desc"
DoCmd.Close acTable, ("Results")
'set a new criteria for baseline testing using Dlookup
basetestString = "[Equipment_ID] = '" & equipID & "' AND [Baseline?] = True _
AND format([Survey_Date],""ddmmyyyy"") < format(" _
& sdate & ",""ddmmyyyy"")"
'set variables
[Forms]![results]![text_A] = Nz(DLookup("[Input]", "[results]", _
basetestString))
I believed (perhaps naively) that DLookup returns the first record it finds that matches the criteria specified. So, my code was designed to sort the table into chronological order, thinking that this would be the order that DLookup would cycle through the records.
However, each time I run the code, I am returned the lowest possibly date that matches the criteria rather than the one closest to sdate. After some playing around, I believe that DLookup uses the primary key as its basis for cycling through the records (the earlier dates are entered earlier, and hence given a primary key using autonumber which is lower than later dates).
This leads to me my questions...
1) I am correct in believing this is what is happening when I am returned the wrong record?
2) Is there a way to use DLookup in the way I am attempting? Can I choose which field is used to order the records for DLookup? Assigning the date field as the primary key is not possible as the dates might not always be unique.
3) Is there any other way I can achieve what I am trying to do here?
Thank you very much
It is always unsafe to rely on an order of records in a relational database. You could use DMax to get the date you need, but I think that in this case a recordset would be quicker.
Dim rs As DAO.Recordset
Dim db As Database
Dim ssql As String
Set db = CurrentDB
ssql=" SELECT input" _
& " FROM results" _
& " WHERE results.[baseline?] = true" _
& " AND results.equipment_id = '" & equipID & "'" _
& " AND results.survey_date = (SELECT" _
& " Max(results.survey_date) " _
& " FROM results" _
& " WHERE results.[baseline?] = true" _
& " AND results.equipment_id = '" & equipID & "'" _
& " AND results.survey_date <#" & Format(sdate,"yyyy/mm/dd") & "#)"
Set rs = db.OpenRecordset(ssql)
strInput = rs("Input")
Debug.Print strInput
You can also check the number of records returned, in case of an error.

DSum with date criteria

I need to count the number of shifts worked by people over the last twelve months. I want to use DateSerial. My code works if I input an actual date, not DateSerial. I tested my code by changing DateSerial to return a date other than twelve months ago but my code always gives the figure for the sum of all data - going back more than twelve months. So it ignores MyDt. Where am I going wrong?
Public Function Shifts() As Integer
Dim MyDt As Date
MyDt = DateSerial(Year(Date), Month(Date) - 12, 1) - 1
Shifts = DSum("Shifts", "tblWorkNew", "GP = " & GPLookup & "And Month > #31/10/2012#") 'This works for any date.
Shifts = DSum("Shifts", "tblWorkNew", "GP = " & GPLookup & "And Month > " & MyDt) 'This only gives all data, i.e. ignores MyDt
End Function
MyDt is Date/Time, but you include it as a string in your DSum criteria argument. So transform the value to a string which the db engine recognizes as the date you intend.
Shifts = DSum("Shifts", "tblWorkNew", _
"GP = " & GPLookup & _
" And [Month] > " & Format(MyDt, "\#yyyy-mm-dd\#"))
I added a space before And because it looked like there was one missing. I assumed Month is the name of a field in your tblWorkNew table, so enclosed it in square brackets to inform the db engine you don't want the Month() function instead.