Date comparison is incorrect - vba

This is just part of a vba code I am writing and simple date comparison is not working. I have one sheet with tons of data and the vba code creates a pivot table. The code runs fine and does filter out all the past dates but it does not filter out (Feb 3 and Feb 4) for some reason (today is Feb 29). It filters out all the other Feb dates properly but its just those two dates. Anyone know what is wrong?
With ActiveSheet.PivotTables("pivottable1").PivotFields("issuedate")
For Each pi In .PivotItems
If pi < Date Then
pi.Visible = False
End If
Next pi
End With

Have you checked that the column type is a date and not a string? Maybe try CDate(pi)?
If that doesn't work please post the dates that aren't working - maybe by doing a Debug.print(pi).

Related

Error When Trying to Filter Pivot Table With Between Dates Using vb.net

I'm automating a number of reports using a vb.net winforms application. I have one report where I need to update the filter on a Date Field to between 2 dates (Monday & Sunday or the week in question).
I'm getting the dates by having the user select an End Date from a DateTimePicker dateStatusEnd
When the code gets to adding the filter I get the below error message:
The dates are valid because I mistakenly thought I had added them in the wrong order but this gave an error saying the end date had to be less then the start date so it's definitely reading them as errors.
Any ideas how I can resolve this? Code snippet below:
xlSht = aWorkBook.Worksheets("RBA Expiry Dates")
Dim xlPivot As PivotTable = xlSht.PivotTables("PivotTable1")
Dim xlPivotField As PivotField = xlPivot.PivotFields("RBA Expiry Date")
xlPivotField.ClearAllFilters()
If dateStatusEnd.Value.Day = 31 AndAlso dateStatusEnd.Value.Month = 12 And dateStatusEnd.Value.Date.ToString("dddd") <> "Sunday" Then
Dim aDate As Date = dateStatusEnd.Value.Date
Do Until aDate.ToString("dddd") = "Monday"
aDate = aDate.AddDays(-1)
Loop
xlPivotField.PivotFilters.Add2(Type:=XlPivotFilterType.xlDateBetween, Value1:=aDate.ToShortDateString, Value2:=dateStatusEnd.Value.Date.ToShortDateString)
Else
xlPivotField.PivotFilters.Add2(Type:=XlPivotFilterType.xlDateBetween, Value1:=dateStatusEnd.Value.Date.AddDays(-6).Date.ToShortDateString, Value2:=dateStatusEnd.Value.Date.ToShortDateString)
End If
In case anyone else comes across this in the future, it turns out that somewhere between opening the file & applying the filter the Pivot has stop recognising the date column as a date column.
Now I just need to figure out why that's happening 😢

SSRS Report to check conditions and hide table data

This one worked in the past and its deployed but all of a sudden it is started throwing an error. In the Tablix properties I have to check these 3 conditions:
=IIF(DATEDIFF("d", Parameters!startDate.Value, Parameters!endDate.Value) > 30 AND Parameters!startDate.Value > Today() AndAlso Parameters!endDate.Value > Today() AND Parameters!startDate.Value >= Parameters!endDate.Value, True,False)
If I choose end date as todays date it is throwing a message but it is also displaying data. Please help me. It worked earlier, it used to show only message saying date is future date. Now it is displaying data also. I don't want the data to be displayed. TIA.
Is this expression in the Hidden property of the tablix?
If so then the way it is written means that all the conditions must be true for it to be hidden. If I've read it correctly, if startDate was yesterday but endDate was tomorrow, the result will be False so the tablix would display.
If you are just trying to test if any date is in the future or the dates are more than 30 days apart then you could do something like this.
=IIF(
DATEDIFF("d", Parameters!startDate.Value, Parameters!endDate.Value) > 30
OR Parameters!startDate.Value > Today()
OR Parameters!endDate.Value > Today()
, True
, False
)

Querying data from quite old IBM iseries AS400 DB2 (date format issue)

I am quite a newbie in querying data from databases and now I am currently having an issue with date format in very old (I don't know exact version) IBM iSeries AS400 DB2 database. My problem is that the date is stored in this DB in three separate columns as whole number (column day + column month + column year) and I need to connect to this DB via ODBC in Excel and filter just a few rows according to desired date span (e.g. from 1st December 2019 until 31st December 2019). In this case I don't want to use PowerQuery to do all the modifications, because the complete table has millions of rows. I want to specify the filter criteria within SQL string so the PowerQuery doesn't have to load all the rows...
My approach was following:
I've created 6 parameter cells in Excel sheet where I simply defined Date From (e.g. cell 1 = '01', cell 2 = '12' and cell 3 = '2019') and Date To (same logic for parameter cells 4, 5 and 6). Then I mentioned these parameter cells in SQL string where I defined:
(Day >= Parameter cell 1, Month >= Parameter cell 2, Year >= Parameter cell 3)
and
(Day <= Parameter cell 4 etc.)
This worked quite good for me, but only when I liked to export just a few hundreds of lines within the same year. But now I am facing to an issue when I like to export data from 1st December 2019 to 31st January 2020. In this case my "logic" doesn't work, because Month From is '12' and Month To is '01'.
I've tried another approach with concat SQL function to create text column like '2019-12-01' and then convert this column to datetime format (with cast to varchar8 first), but it seems that this approach doesn't work for me, because everytime I get an error which says: "Global variable DATETIME not found".
Before I post you some of my code, could I ask you for an advise, if you can think of a better solution or approach for my issue?
Many thanks and have a great day :-)
A simple solution would be
select * from table where year * 100 + month between 201912 and 202001

Comparing Date Range Excel VBA

UPDATED WITH ANSWER: I found an answer to my question. I'll place a simplified version below the original question here, just to make it easy, with a more detailed version below as the accepted answer.
I'm writing a VBA function to filter a pivot table by a date range entered by the user. For some reason, it is not returning the results expected.
The dates being compared are in two different date formats. The user-entered dates are in mmmm yyyy format (October 2013). When this value is pulled into the macro for comparison, it is translated correctly as 10/1/2013. The pivot table dates are in mmm yy format (Oct 13). When I call on this date with the code PivotItem.Value it seems to be translating the date as a string "Oct 13."
I can't quite figure out what the macro is doing, as it behaves somewhat erratically. If I run it for October 2011 to October 2013, it returns all months from Jan to September for every year, 2008, 2009, 2010, etc. If I run it for June 2013 to October 2013, it returns June to September for every year. Furthermore, in each example, the macro continues to run past the maximum range of data in the pivot table and gets an error. When I debug, the macro is trying to set the visibility to 'true' for a date that doesn't even exist in the pivot table (IE for Jan 2014 when the data only goes through Oct 2013). No idea why that's happening.
Below is the code. Any insight would be greatly appreciated.
UPDATE:
So the problem is definitely the date format. If I change the field settings in the pivot table to the date format mm/dd/yyyy (10/1/2013), then the macro works exactly as expected. This would be a simple fix to the problem except that the table is feeding a chart seen in the user dashboard, which I would really like to be in the format mmm yy, since it looks much cleaner. Is there a simple way to convert the format to mm/dd/yyyy inside the macro for the comparison, then back to the desired format once complete?
And I would still like to understand why a different date format is returning such different results, when the raw data being compared is the same, and both are formatted as dates, not like date vs text or something.
Sub filterPivotDate(pt As PivotTable, strtDate As Date, endDate As Date)
Dim pf As PivotField
Dim pi As PivotItem
'Clear current date filter
Set pf = pt.PivotFields("Date")
pf.ClearAllFilters
'Set new date filter
For Each pi In pf.PivotItems
If pi.Value >= strtDate And pi.Value <= endDate Then
pi.Visible = True
Else
pi.Visible = False
End If
Next pi
end sub
ANSWER UPDATE:
I replaced the loop I was using to set the filter with the following line of code:
pf.PivotFilters.Add Type:=xlDateBetween, Value1:=strtDate, Value2:=endDate
This solved the issue I was having with the date format. More information in the accepted answer below, as well as at this website
I might be wrong, but one of your < characters looks backwards- don't you want start dates Greater than the variable?
You could try converting the string date value first:
Dim dateValue as Date
'Set new date filter on all pivot tables
For Each pt In ws.PivotTables
Set pf = pt.PivotFields("Date")
For Each pi In pf.PivotItems
If IsDate(pi.Value) Then
dateValue = CDate(pi.Value)
If dateValue < strtDate Or dateValue > endDate Then
pi.Visible = False
Else
pi.Visible = True
End If
End If
Next pi
Next pt
'call this function
Function IsDate(byval thisDateString as String) As Boolean
On Error Goto ErrorHandler
Dim d as Date
d = CDate(thisDateString)
IsDate = true
Exit Function
ErrorHandler:
IsDate = false
End Function
I found some additional information about setting pivot table filters via VBA that improves upon the original code and solves the issue I was having. I decided to post it, as I found the information extremely helpful.
There are a lot of different filters you can set with simple, one line commands, rather than complicated loops which parse all the data and set visibility manually based on a condition as I was doing before. Below is the updated code, which also solved the issue I was having with the date formatting.
There is some really useful information at this link to the globaliconnect website about different pivot table filter settings you can set using VBA.
I'm still not certain why the date was behaving weird before when doing the comparison in a loop, but dates are just kinda like that I guess...
Sub filterPivotDate(pt As PivotTable, strtDate As Date, endDate As Date)
Dim pf As PivotField
Application.ScreenUpdating = False
'Clear date filter and set new filter
Set pf = pt.PivotFields("Date")
pf.ClearAllFilters
'I REPLACED THE LOOP WITH A SINGLE LINE TO SET A FILTER BETWEEN TWO DATES
pf.PivotFilters.Add Type:=xlDateBetween, Value1:=strtDate, Value2:=endDate
Application.ScreenUpdating = True
End Sub

Calculating Months

I have an application where the user selects the dates of a first statement and a last statement. Example, first statement = 1/1/08, last statement = 12/1/08, should equal 12 statements.
However, when using the following code, the result is 11:
numPayments = DateDiff(DateInterval.Month, CDate(.FeeStartDate), CDate(.FeeEndDate))
Is there another way to calculate this, or do I have to be stuck with adding 1 to the result?
Add 1, as you write. ;)
The difference between 1/1/2008 and 12/1/2008 is 11 months. No changing that. ;)
Yes, you'd always have to add one though you may be able to add one to the end date or subtract one from the start date to also get this effect. Consider the case where the start and end dates are the same. Their difference is 0 but you'd still want 1 statement to show just to note one odd case.
Well, the number of months between Jan 1st and Dec 1st is 11... what you're looking for is the difference of months +1. So just add one :)
Also, the DateDiff function you're using is a VB6 hold-over. Better to express it like this:
numPayments = (Date.Parse(.FeeEndDate) - Date.Parse(.FeeStartDate)).TotalMonths + 1
You could try this one. Hope this is very helpful.
Dim myDate As Date
Dim dateNow As Date
Dim nextMonth As Date
myDate = Now
dateNow = Format(myDate, "MM/dd/yyyy")
nextMonth = DateAdd(DateInterval.Month, 5, dateNow) 'compute the next 5 months from date now. Let say, #12/6/2012# the result will be #5/6/2013#
MessageBox.Show(DateDiff(DateInterval.Month, dateNow, nextMonth) & "months==> " & nextMonth)
'This will count the number of months interval. The result will be 5 months=>> #5/6/2013 because we count december to may.