Access VBA Compare dates not working - ms-access

I am having trouble comparing dates. The if statement in my code is saying the endDate is not less even though it is. For example, if the endDate is 2/20/2017 and startDate 2/22/2017 the if statement says endDate is not lest but it is.
Dim startDate As Date
Dim endDate As Date
startDate = DateValue(Me.dueDateTxt)
endDate = DateValue(Me.shippedDate)
If (endDate < startDate) Then
Debug.Print "It is less"
Else
Debug.Print "not less"
End If
I have also tried
If Me.dueDateTxt < Me.ShippedDate Then
If CDate(startDate) < CDate(endDate) Then
If Format(startDate, "mm/dd/yyyy") < Format(endDate, "mm/dd/yyyy") Then
If DateDiff(d, startDate, endDate) > 0 Then
I am missing something somewhere thank you in advance for the help!
EDIT: I figured out what the problem was. I have a function to eliminate holidays and weekends. That function was swaping my startDate and endDate. Thank you everyone for your help and suggestions.

Your first block of code works fine for me.
Have you set the format of the text boxes(?) as 'Short Date' for example?

Related

VB.NET How to create a reminder by checking database saved dates

I have this few line of codes where I save the date from datetimepicker to my database column REMINDER.
myCommand.CommandText = "Update kup_table SET REMINDER = #reminder Where ID = #theIDD"
myCommand.Parameters.AddWithValue("#reminder", DateTimePicker1.Value.Date)
myCommand.Parameters.AddWithValue("#theIDD", theID)
myCommand.ExecuteNonQuery()
In my database, the date is saved in this format 2015-12-14 00:00:00 since the datatype is DATETIME.
How do I compare it with the date now? If the saved date and today date are a match, then a reminder will go off.
I have tried using this sql command but having still having trouble where the reminder is always zero. Thanks in advance.
myCommand.CommandText = "Select COUNT(*) from kup_table Where REMINDER BETWEEN DATE() AND DATEADD('d', 1, DATE())"
mySqlConn.Open()
Console.WriteLine("Connected.")
count = myCommand.ExecuteScalar()
MsgBox("You have " + count.ToString + " reminder(s).")
Select COUNT(*) from kup_table Where DATE(REMINDER) = DATE(NOW())
The DATE() function returns the date part of the datetime only. (e.g. 2015-12-14)
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date

Access Query. If records Due Date = Last Week Insert Yes in Cell

Good morning All,
I am working on the following however, I can't figure it out for the life of me. I have table that contains a bunch of due dates. What I am trying to do is add a query that adds another field and inserts a yes if the date equals a day in last week. Honestly I need it to insert yes as long as it does not = this week.
I've tried using:
Urgent: IIf([Due Date]=[Due Date]
Between
DateAdd("d",1-Weekday(Date()) 7, Date()) And
DateAdd("d",1-Weekday(Date())-1, Date()),"Yes","")
with no luck. What am I missing here?!
Thanks all. Cheers.
Here's how to return Urgent if 'not this week' means previous Saturday and before. Not sure how you would do it without code.
Helper Function to get the first day of this week based on current date. Paste it into a new or existing global module.
Function FirstDateOfTheWeek() As Date
Dim dt As Date
If Weekday(Date) = vbSaturday Then
FirstDateOfTheWeek = DateAdd("y", -6, Date) 'today is Saturday? then return previous Sunday
ElseIf Weekday(Date) = vbSunday Then
FirstDateOfTheWeek = Date 'today is Sunday? then return Sunday because its the first day of the week
Else 'weekday, so just go backwards until we hit previous sunday's date
dt = Date
While Weekday(dt) <> vbSunday
dt = DateAdd("y", -1, dt)
Wend
FirstDateOfTheWeek = dt
End If
End Function
An IsUrgent function to be called from query. Paste it into a new or existing global module.
Function IsUrgent(dt As Variant) As String
If IsNull(dt) Then 'if null date is passed then return blank string; Variant chosen instead of date for this case; change it to N/A if you want?
IsUrgent = ""
Exit Function
End If
If dt < FirstDateOfTheWeek Then
IsUrgent = "Yes"
Else
IsUrgent = ""
End If
End Function
The Query Column calling IsUrgent() function:
IsUrgent: IsUrgent([Due Date])

how to change Access date variable's format

I have a user inputed date format of mm/dd/yyyy. I want to use this input in a query to act as a filter (start and end time). The actual date stored in the datebase was set with now(), so it has the format mm/dd/yyyy XX:XX:XX AM/PM.
How can I use these inputed dates in my filter? (When I tried out an mm/dd/yyyy input I was returned a Report with no values, but if I added the time, it worked, but I don't want the user to have to enter the time.)
Right now I am using simple input boxes for the input. I really would like to create a calendar popup (and I see tutorials online). Would the solution change if I changed over to a Calendar?
EDIT:
Here is my code, to make it eaiser to understand the issue.
Dim startDate As Date
Dim endDate As Date
startDateString = InputBox("Enter a start date.")
endDateString = InputBox("Please enter and end date.")
Reports![rpt_Inventory_Update].RecordSource = "MyQuery"
Reports![rpt_Inventory_Update].Filter = "Modification_Date BETWEEN #" & startDate & "# AND #" & endDate & "#"
Reports![rpt_Inventory_Update].FilterOn = True
When you compare to the field with Now(), you could change it to be compared to DateValue(Now())
Now() = Date() returns False
DateValue(Now()) = Date() returns True
I figured it out. This is my new code:
startTime = TimeValue("00:00:00")
endTime = TimeValue("23:59:59")
startDate = startDate + startTime
endDate = endDate + endTime
Reports![rpt_Inventory_Update].RecordSource = "MyQuery"
Reports![rpt_Inventory_Update].Filter = "Modification_Date BETWEEN #" & startDate & "# AND #" & endDate & "#"
Reports![rpt_Inventory_Update].FilterOn = True
This makes sure that the start and end dates in the query have a full time stamp, and thus the query works!

calculate how many weekend days inside date?

I need to calculate how many weekend days inside 2 dates? what I mean is that I have 2 dates and want to know the count of Saturdays & Sundays between these dates.
I have the 2 dates on each record (from date - to date) and want to query the count of weekends.
The following VBA function will allow you to run Access queries of the form
SELECT CountWeekendDays([from date], [to date]) AS WeekendDays FROM YourTable
Just create a new Module in Access and paste the following code into it:
Public Function CountWeekendDays(Date1 As Date, Date2 As Date) As Long
Dim StartDate As Date, EndDate As Date, _
WeekendDays As Long, i As Long
If Date1 > Date2 Then
StartDate = Date2
EndDate = Date1
Else
StartDate = Date1
EndDate = Date2
End If
WeekendDays = 0
For i = 0 To DateDiff("d", StartDate, EndDate)
Select Case Weekday(DateAdd("d", i, StartDate))
Case 1, 7
WeekendDays = WeekendDays + 1
End Select
Next
CountWeekendDays = WeekendDays
End Function

How to get start and end of previous month in VB

Im trying to create some VB code that will get the start and end of the previous month.
Im able to the current month which is just:
Month(DateValue(Now))
which would return 3. From there I can take away 1 to give me 2 meaning February. This is fine but what about when I Im in January and I repeat this and it gives me zero - my code will fail. Any one know how to get the previous months start and end day then?
Thanks
The first day of the previous month is always 1, to get the last day of the previous month, use 0 with DateSerial:
''Today is 20/03/2013 in dd/mm/yyyy
DateSerial(Year(Date),Month(Date),0) = 28/02/2013
DateSerial(Year(Date),1,0) = 31/12/2012
You can get the first day from the above like so:
LastDay = DateSerial(Year(Date),Month(Date),0)
FirstDay = LastDay-Day(LastDay)+1
See also: How to caculate last business day of month in VBScript
I have similar formula for the First and Last Day
The First Day of the month
FirstDay = DateSerial(Year(Date),Month(Date),1)
The zero Day of the next month is the Last Day of the month
LastDay = DateSerial(Year(Date),Month(Date)+ 1,0)
firstDay = DateSerial(Year(DateAdd("m", -1, Now)), Month(DateAdd("m", -1, Now)), 1)
lastDay = DateAdd("d", -1, DateSerial(Year(Now), Month(Now), 1))
This is another way to do it, but I think Remou's version looks cleaner.
Try this
First_Day_Of_Previous_Month = New Date(Today.Year, Today.Month, 1).AddMonths(-1)
Last_Day_Of_Previous_Month = New Date(Today.Year, Today.Month, 1).AddDays(-1)
This works reliably for me in my main sub.
Dim defDate1 As Date, defDate2 As Date
'** Set default date range to previous month
defDate1 = CDate(Month(Now) & "/1/" & Year(Now))
defDate1 = DateAdd("m", -1, defDate1)
defDate2 = DateAdd("d", -1, DateAdd("m", 1, defDate1))
Try this to get the month in number form:
Month(DateAdd("m", -3, Now))
It will give you 12 for December.
So in your case you would use Month(DateAdd("m", -1, Now)) to just subract one month.
Just to add something to what #Fionnuala Said, The below functions can be used. These even work for leap years.
'If you pass #2016/20/01# you get #2016/31/01#
Public Function GetLastDate(tempDate As Date) As Date
GetLastDate = DateSerial(Year(tempDate), Month(tempDate) + 1, 0)
End Function
'If you pass #2016/20/01# you get 31
Public Function GetLastDay(tempDate As Date) As Integer
GetLastDay = Day(DateSerial(Year(tempDate), Month(tempDate) + 1, 0))
End Function
Public Shared Function GetFOMPrev(ByVal tdate As Date) As Date
Return tdate.AddDays(-(tdate.Day - 1))
End Function
Public Shared Function GetEOMPrev(ByVal tdate As Date) As Date
Return tdate.AddDays(-tdate.Day)
End Function
Usage:
'Get End of Month of Previous Month - Pass today's date
EOM = GetEOMPrev(Date.Today)
'Get First of Month of Previous Month - Pass date just calculated
FOM = GetFOMPrev(EOM)