AND statement in Date Range Filter - vba

I have a form, with a data sheet subform. This subform has rows with WageDate and TipDate. I have the follwing bit of code to filter the the records to display the records with the WageDate that falls in the range:
Private Sub btnDateRange_Click()
Dim Filter As String
Filter = "[WageDate] Between #" & Format(Me!TxtStartDate.Value, "yyyy\/mm\/dd") & "# And #" & Format(Me!txtEndDate.Value, "yyyy\/mm\/dd") & "#"
Me!sbfrm_qryDeliveries.Form.Filter = Filter
Me!sbfrm_qryDeliveries.Form.FilterOn = True
End Sub
My question is how do I change this up so that it also filters the TipDate at the same time, so that the resulting records would be those with both WageDate AND TipDate that fall in the selected range? the records might not be equal. That is, one record may have a WageDate that falls out of the range, but a TipDate that does.
And once I get that figured out, is there a way to selectively SUM a column based on that date? For instance. Let's say I filter a date range and four records are returned two have WageDates that fall in the criteria, and two have TipDates thats fall in the criteria. WageDate and TipDate are both in the same datasheet. So if I were to just do a SUM of Wage and TipAmount columns I'd get a sum which would include numbers in those columns that don't really belong. The TipAmount column might have an amount come up because the WageDate fell in the range but not the TipDate. So I need to be able to SUM just the rows in each of those columns that ONLY fall within the selected date range. I hope this wasn't too confusing. Maybe there's a better way to do this completely than the way I have it, I don't know. Oh, for information, the subform is based from a query, and both wages and tips are in their own separate tables. tblWages, tblTips

the resulting records would be those with both WageDate AND TipDate
that fall in the selected range?
Private Sub btnDateRange_Click()
Dim Filter As String
Filter = "([WageDate] Between #" & Format(Me!TxtStartDate.Value, "yyyy\/mm\/dd") & "# And #" & Format(Me!txtEndDate.Value, "yyyy\/mm\/dd") & "#) " & _
"And ([TipDate] Between #" & Format(Me!TxtStartDate.Value, "yyyy\/mm\/dd") & "# And #" & Format(Me!txtEndDate.Value, "yyyy\/mm\/dd") & "#)"
Me!sbfrm_qryDeliveries.Form.Filter = Filter
Me!sbfrm_qryDeliveries.Form.FilterOn = True
End Sub
However, though not clear, you probably mean OR here:
one record may have a WageDate that falls out of the range, but a
TipDate that does.
Filter = "([WageDate] Between #" & Format(Me!TxtStartDate.Value, "yyyy\/mm\/dd") & "# And #" & Format(Me!txtEndDate.Value, "yyyy\/mm\/dd") & "#) " & _
"Or ([TipDate] Between #" & Format(Me!TxtStartDate.Value, "yyyy\/mm\/dd") & "# And #" & Format(Me!txtEndDate.Value, "yyyy\/mm\/dd") & "#)"
Note:
You only need to Format data you plan on displaying.
This is a plain wrong statement. You must format a date value as a string expression to concatenate it with the SQL command. If you don't, an implicit cast will be forced on you using whatever the local settings might be, and you loose control. Applying CDate or DateValue doesn't change that and will here be superfluous or even a source of error as they don't accept Null values.

Related

How do I compare values from one datetime index to a range of other other datetime indexes?

I am using pandas and mplfinance to work with a stock market data set. How can I compare the current index to the previous(x) indexes?
For example I want to find a divergence between the current price and an indicator I am using. (Divergence is when the price is moving lower than the lowest value ‘x’ periods ago and the indicator sharing the same xaxis is not lower than the lowest value ‘x’ periods ago. X being a range of period, in this case a range of datetime indexes).
In order to do that I need to look backwards at the prior data to see if the current value of price is lower than the lowest value in the previous 15 periods. If true, I would need to check if the current value in the indicator is higher than the lowest value in the previous 15 days.
I can write a long hand version of this but it’s really not efficient to rewrite it if I want to use a different time frame or indicator.
This is the long form I managed to slap together:
df[‘bullDiverg’] = np.where( df.close <
((df.close.shift(1) & df.close.shift(2) & df.close.shift(3) & df.close.shift(4) & df.close.shift(5) & df.close.shift(6) &
df.close.shift(7) & df.close.shift(8) & df.close.shift(9) & df.close.shift(10) & df.close.shift(11) & df.close.shift(12) & df.close.shift(13) & df.close.shift(14) & df.close.shift(15))
&
(df.macd.shift >
(df.macd.shift(1) & df.macd.shift(2) & df.macd.shift(3) & df.macd.shift(4) & df.macd.shift(5) & df.macd.shift(6) &
df.macd.shift(7) & df.macd.shift(8) & df.macd.shift(9) & df.macd.shift(10) & df.macd.shift(11) & df.macd.shift(12) & df.macd.shift(13) & df.macd.shift(14) & df.macd.shift(15))),1,0 )
A function where I enter the Datetime df price and indicator Values that creates the bullish divergences Col so I can add it to my existing data would be ideal but just a more efficient way to write what I did above would be appreciated.

Trying to Find Duplicate Records in Access Error

I am making a databse for a sports club,
When filling out a form, they input the facility ID, start time, end-time and date.
What I am trying to do is when they enter the end time box, the function scans through the entries on the 'Bookings' Table where all the data from this form is stored, to see if the facility is booked out at this time. ( For dtermining if it is booked out at a certain time, if the start time or the end time on table is between what is filled in on the form, an error is thrown
The code is shown below:
Private Sub EndNon_AfterUpdate()
Dim criteria As String
criteria = _
"Non-PlayingFacilityID= " & Me.NonPlayID.Value & " " & _
"Date(Non-PlayingFacility)= " & Me.DateNon.Value & _
" " & "AND [StartTime(Non-PlayingFacility)] Between Me.StartNon.Value And Me.EndNon.Value OR [EndTime(Non-PlayingFacility)] Between Me.StartNon.Value And Me.EndNon.Value "
If DCount("*", "Bookings", criteria) > 0 Then
MsgBox "Unfortunately, this facility is booked at this time"
Me.Undo
End If
End Sub
Syntax error is thrown when I run this, not sure why.
Any help would be much appreciated
It probably highlights this invalid syntax:
"Date(Non-PlayingFacility)= " & Me.DateNon.Value & _
Perhaps you mean:
"DateValue([Non-PlayingFacility])= " & Format(Me!DateNon.Value, "\#yyyy\/mm\/dd\#") & _
The remaining date comparisons need to be concatenated and formatted similarly.
Addendum - given the obscure field name:
"[Date(Non-PlayingFacility)]= " & Format(Me!DateNon.Value, "\#yyyy\/mm\/dd\#") & _
The format is needed to create a valid string expression in SQL for the date value. This is independent of a format applied for display.

Why does my SQL statement not find a match with the WHERE statement below?

I'm attempting to pull data from my MS Access database via an Excel SQL statement. It does NOT give me any errors, however it also does not pull the data I'm searching for.
If items(u, 1) is text (ex. 308-203BL), then it works perfectly.
I've tried both comparing them as text and as numerical, but neither way find any matches when items(u, 1) is 19310.
This compares it as text...
LEFT(Item," & Len(items(u, 1)) & ") = '" & items(u, 1) & "'"
this compares it as numerical...
VAL(LEFT(Item," & Len(items(u, 1))) & ") = " & items(u, 1)
I have verified that there are records in the DB that match the given criteria.
items() is an array populated from a 1 column table on the sheet by items = Range("Items").Value.
Using these two SKU's as examples, the first working, the second not, the array would be as follows. .
SKU by SKU, they're fed into the SQL as below.
With the input in the example, the output I receive is an array populated only the sales for the second item. The order I put the SKU's in the table doesn't change that result. I have tested it with multiple SKU's, and no matter how many I use, it returns the proper information, with the exception of not returning any results for any numerical SKU's.
The field for Item in the DB is a short text, which is why I used '" & items(u, 1) & "'" to convert the SKU to text when I was trying to match it as text, and Val() to convert the field to a value when trying to match it as a number. Both gave me 0 record counts in the function, but did not give me a data type error.
Below is the portion of my code which determines the SQL string, and a bit afterwords which basically stuffs it into a UDF which pulls the info from the DB and puts it into an array for me. Aside from not finding a match when items(u,1) is numerical, it works perfectly.
DBString = "SELECT Invoice, Line, Inv_Date, Sales_Order, SOLine, SO_Date, CustID, Item, Part_Description, Ship_Qty, Price, Ext_Sales FROM `" & Year(tabledate) & "-" & Format(tabledate, "mm") & "` WHERE Inv_Date BETWEEN #" & Sdate & "# AND #" & Edate & "# AND LEFT(Item," & Len(items(u, 1)) & ") = '" & items(u, 1) & "'"
SalesHolder = PullFromDB(DBString, SGMDB)
I've also tried the below code instead, to force it to compare as a number instead of text, which also doesn't give me any errors, but doesn't find a match.
DBString = "SELECT Invoice, Line, Inv_Date, Sales_Order, SOLine, SO_Date, CustID, Item, Part_Description, Ship_Qty, Price, Ext_Sales FROM `" & Year(tabledate) & "-" & Format(tabledate, "mm") & "` WHERE Inv_Date BETWEEN #" & Sdate & "# AND #" & Edate & "# AND VAL(LEFT(Item," & Len(items(u, 1))) & ") = " & items(u, 1)
SalesHolder = PullFromDB(DBString, SGMDB)
Below is the UDF itself which pulls the info from the DB. It works quite nicely.
Function PullFromDB(DBStr As String, DBLoc As String) As Variant
Dim TheDB As Recordset, DBHolder() As Variant
Set TheDB = OpenDatabase(DBLoc).OpenRecordset(DBStr)
If TheDB.RecordCount = 0 Then GoTo theexit
TheDB.MoveLast
TheDB.MoveFirst
ReDim DBHolder(0 To TheDB.RecordCount, 1 To TheDB.Fields.Count) As Variant
For k = 1 To UBound(DBHolder, 2)
TheDB.MoveFirst
For j = 0 To UBound(DBHolder)
If j = 0 Then
DBHolder(j, k) = TheDB.Fields(k - 1).Name
Else
DBHolder(j, k) = TheDB.Fields(k - 1).Value
TheDB.MoveNext
End If
Next j
Next k
theexit:
TheDB.Close
Set TheDB = Nothing
PullFromDB = DBHolder
On Error GoTo -1
End Function
The expected result is to populate the array SalesHolder with the information that matches the criteria.
What am I missing? I'm going blind trying to find it.
Thank you all for your responses to this, it turns out I was completely hunting for the wrong problem. The code I posted was actually correct, the issue was with the format of Inv_Date field in the DB. I had mistakenly entered the last couple of months as text instead of date, so the WHERE Inv_Date BETWEEN #" & Sdate & "# AND #" & Edate & "# portion of my SQL didn't match anything.
I hadn't identified that this was the issue earlier due to the timing of the sales of the SKU's themselves, which was purely coincidence. When I expanded the dates range, I found that it did return results for the numerical SKU, but both numerical and text SKU's cut off two months ago.
Thank you again!

Excel vba Items.restrict 2 conditions

I need help in how to put this in a restrict syntax. the original restrict works:
Set myTasks = Fldr.Items.Restrict("[ReceivedTime]>'" & Format(Date - daysAgo, "DDDDD HH:NN") & "'")
Now i was told that it's possible to put 2 filter in a restrict so i tried:
Set myTasks = Fldr.Items.Restrict("[ReceivedTime]>'" & Format(Date - daysAgo, "DDDDD HH:NN") & "' And Not [Subject] like '%Undeliverable%'")
I tried the code above but i'm getting an error "Condition is not Valid". Basically, condition 1 filters emails based on the date it was received which does work alone. The 2nd condition that i need is to make sure that the loop will ignore emails that has "Undeliverable" in the subject line. Please help on how to put the correct syntax.
To answer the question you asked, rather than the question you want answered.
Two restricts can be applied one after the other but both have to work. In this case it appears the Not Subject filter may not be possible.
You can first filter the items in the folder, if it is possible, with a Not version of this filter "#SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & "like '%Undeliverable%'" as described in the comments. https://stackoverflow.com/a/27350173/1571407
Set myTasks = Fldr.Items.Restrict(Not .... '%Undeliverable%'")
Second, filter Mytasks, not Fldr:
Set myTasks = myTasks.Restrict("[ReceivedTime]>'" & Format(Date - daysAgo, "DDDDD HH:NN") & "'")

date range issue display in crystal report

I want to generate report from 01-Feb-2016 to 31-Mar-2016. Using formula
{cryRpt.RecordSelectionFormula = "{product_details.date11} >= #" &
DateTimePicker1.Text & "# and {product_details.date11} <= #" &
DateTimePicker2.Text & "#"}
but it is still not providing proper sequence, sometime places 01-Mar-2016 in between, same with 29-Feb-2016, using group in crystal report but still not success, help me out
Between these # crystal treats as datetime and not date values to get correct values you need to convert to date try like this:
{cryRpt.RecordSelectionFormula = "{product_details.date11} >=CDate( #" &
DateTimePicker1.Text & "#) and {product_details.date11} <= CDate(#" &
DateTimePicker2.Text & "#"})
I haven't checked the syntax, check when you are using in record selection formula