How to determine if a date is in the past? - vba

I have an Excel workbook for tracking backup success. We have a number of sheets with the date in the first column, and macros to do calculations, based on whether the date is in the past or not. (The macros either hide or reveal the appropriate rows.)
This has been working until yesterday. I assume because the macros are doing a string comparison, rather than a date comparison. ("01/01/2013" is smaller than "12/31/2012", when viewed as strings.)
Is there a native way to compare dates in VBA, or do I need to convert the dates into "yyyy/mm/dd" first (a how to would be nice).
A2 is the cell with the first date we started using this new version of the spreadsheet, and A454 is the last date I extended the spreadsheet to, corresponding to the end of this year.
Sub ShowAll()
Dim cell As Range
For Each cell In Range("A2:A454")
cell.EntireRow.Hidden = False
Next
End Sub
Sub RevealPast()
Dim cell As Range
For Each cell In Range("A2:A454")
If cell.Value < Date Then
cell.EntireRow.Hidden = False
End If
Next
End Sub
Sub HideFuture()
Dim cell As Range
For Each cell In Range("A2:A454")
If cell.Value >= Date Then
cell.EntireRow.Hidden = True
End If
Next
End Sub

Try the cDate function.
something along the lines of:
If CDate("02/01/2013") > Date (or Now() if you want today's date) Then
...
So, in your example:
If cDate(cell.Value) >= Date Then
I hope I understand your question correctly and hope this helps...

I know this is a bit different from what you asked but this might help someone someday. If there is an hour added to the date (3/5/2014 8:00:00 AM) and you would like to compare with your date you can:
'X being the date you want to compare
x = CDate(x) 'formatting the date using the CDate function
x= Format(x, "MM/DD/YYYY") 'formatting the date by dropping the hour
x= CDate(x) 'formatting the date again
If x <= Date Then
...

I follow your answer and No ! No ! And No!
On Excel VBA, It's wrong ! you need to format the date like "2020/07/18 09:48:51" to can compare
So first get Date variable with CDate() function, and after, you can compare like that. Else it's not working.
If Format(MyFileDate, "yyyymmdd hhnnss") >= Format(ReportStart, "yyyymmdd hhnnss") And Format(MyFileDate, "yyyymmdd hhnnss") < Format(ReportEnd, "yyyymmdd hhnnss") Then

Related

Find Date() with Application.Match()

I'm trying to find in a row the date of today (I'm using VBA Date to get today's date) But Application.Match doesn't find anything.
The code I'm using is this:
Debug.Print Application.WorksheetFunction.Match(Date, Range("5:5"), 0)
The dates in row 5 are generated by formulas, so I have to search the values.
It really depends on how you are passing the date. In general, in .Match() the best way is to look for a specific numeric:
Public Sub TestMe()
Range("E5") = Clng(Date)
Debug.Print Application.Match(Clng(Date), Range("5:5"), 0)
Range("E5") = ""
Range("C5") = Clng(Date)
Debug.Print Application.Match(Clng(Date), Range("5:5"), 0)
End Sub
Sometimes the date system in Excel are behaving a bit strangely:
VBA treating dates differently in Excel 2016? Is there any documentation about this?
Range.Find not making a difference between January and November (February and December) in VBA Excel
A bit more about Dates in Excel (joelonsoftware.com)
Convert your date to Long:
Debug.Print Application.WorksheetFunction.Match(CLng(Date), Range("5:5"), 0)
You can't use MATCH() with a VBA Date like this. Instead use a Long:
Sub INeedADate()
MsgBox Application.WorksheetFunction.Match(CLng(Date), Range("5:5"), 0)
End Sub
The above is an example of both the worksheet use of MATCH() and the VBA use.
Don't use Match() for comparing dates, it's only for strings.
You can use the functions Year(), Month() and Day(): if year, month and day are equal, then the date is equal.

Date display vs date format VBA

I think that I try to do something what is impossible. I have in range A1:A5 some dates. These cells have to have date format, because I’d like to check if they are bigger or smaller than certain date. Moreover I’d like to display these dates in a range A1:A5 in a following format: yyyy.mm. I think that there is no way to kill two birds with one stone.
Public Sub test()
Range("A1:A5").NumberFormat = "yyyy.mm"
Range("A1:A5") = Format(Date, "yyyy.mm")
If IsDate("A2") Then
Range("B2") = "OK"
End If
End Sub
Range("B1:B5").NumberFormat = "yyyy.mm" change the cells format on custom (yyyy.mm) but the dates are still displayed in unchanged form (yyyy.mm.dd)
Range (“A1:A5”) = Format(Date, “yyyy.dd”) displays the dates yyyy.mm but the year and month has been changed to 1905.07. Moreover the dates do not have Date format but Custom.
Is is really not possible to display a date like yyyy.mm but in date format (so that in formular bar the date is displayed as dd.mm.yyyy or another way around) to be able to compare them with different dates?
Best regards,
Neke
First of all, using points within dates can be a problem, because "2017.05" is interpreted by Excel as a number.
You can reformat the dates into "yyyy/mm" by using something like this:
For Each r In Range("A1:A5")
r.Value = VBA.Format(r, "yyyy/mm")
Next r

changing date fromat from mm/dd/yyyy to dd/mm/yyyy VBA

So I know this question has been asked a couple of times over, but I believe my situation is a bit different (happy to be proven wrong of course!)
Here is the data flow: a user types a date in a date in a form. They then click a button. My macro then takes that date, runs it through the following function:
Function AddWeekDays(StartDate As Long, Days As Long) As Date
Dim i As Long
Dim d As Date
d = StartDate
i = 0
While i < Days
d = DateSerial(Year(d), Month(d), Day(d) + 1)
If Weekday(d, vbMonday) < 6 Then
i = i + 1
End If
Wend
AddWeekDays = d
End Function
Then it formats the date to change it from mm/dd/yyyy to dd/mm/yyyy in the following way:
Dim deadline As Date
Dim deadline_formatted As Date
Dim DateReceived As String
Dim DateConverted As Date
DateReceived = txt_DateReceived.Text
DateConverted = Format(DateReceived, "dd/mm/yyyy")
deadline = AddWeekDays(DateValue((CStr(DateConverted))), 9)
deadline_formatted = Format(deadline, "dd/mm/yyyy")
However, the deadline_formatted value is still coming out in the mm/dd/yyyy format.
As an example, when a user enters 01/05/2017 the program should return deadline_formatted = 12/05/2017, but it returns deadline_formatted = 05/12/2017
I have tried changing the variable type to string to see if that made a difference (it didn't), and have tried directly converting the deadline variable to the required format by using the following code:
deadline = Format(AddWeekDays(DateValue((CStr(DateConverted))), 9),"dd/mm/yyyy")
which still returns the incorrect format.
Can anybody out there suggest either:
How to fix the formatting issue to get the deadline_formatted into the format dd/mm/yyyy
OR
suggest a "workaround" to flip the "dd" with the "mm" (not ideal obviously, but if it works, it works!)
Thanks for any advice!
The best way to solve this issue is to actually change your computer's default date/time format to match the method used by the users. (In comments it is stated that the users are Australians but your company is US-based, so the default is probably currently set to be the USA's "mm/dd/yyyy" format.)
By ensuring that the computers date/time format is correct, it will allow you to process a date as a Date, and it can be stored in Excel cells as a Date, which then allows any of the Australian users to see it displayed as "dd/mm/yyyy" format while a USA-based colleague would see it displayed as "mm/dd/yyyy".
There is a financial risk to your company caused by forcing users to interact with software using an unfamiliar date system, as accidental entering of dates in the wrong formats can lead to major errors downstream, so it is in the company's best interest to allow you to change the settings to be relevant to the users.
It is not directly related to your problem, however I believe it might fix your issues. The manual calculation of adding week days might be the problem here.
There is a built in function to add workdays. You can include/exclude weekends/holidays. The following code replaces your above mentioned code.
Sub AddWeekDays()
Dim deadline As Date, deadline_formatted As Date
deadline = txt_DateReceived.Value
deadline_formatted = Format(Application.WorksheetFunction.WorkDay(deadline, 9), "dd/mm/yyyy")
'debug.print deadline_formatted
End Sub
the result to be String.
Dim deadline As Date
Dim deadline_formatted As String '<~~ change string
Dim DateReceived As String
Dim DateConverted As Date
txt_DateReceived = "01/05/2017"
DateReceived = txt_DateReceived
DateConverted = Format(DateReceived, "dd/mm/yyyy")
'deadline = AddWeekDays(DateValue((CStr(DateConverted))), 9)
deadline = AddWeekDays(CLng(DateConverted), 9) '<~~ change Long
deadline_formatted = Format(deadline, "dd/mm/yyyy")
I wouldn't bother about the regional settings. Instead, make sure that all dates are captured as Date() or Now() values (42123 or 42123.5555). On the output side such values can be presented in any format you wish.
To ensure that dates are entered correctly my preferred way is to use a date picker. If that can't be done make no rules for entering the date at all, working on the presumption that each user will know how to enter a date on his/her machine. Add a date check, like ISDATE(), which will catch some input errors but not all. You don't need to catch all. You only need to teach users how to input dates on their respective PCs.
With this line you don't need anything else.
Range("E:E").TextToColumns FieldInfo:=Array(0, xlDMYFormat)
'1.2.2019 -> 01/02/2019
'2,3,2019 -> 02/03/2019
'3-4-2019 -> 03/04/2019
'4*5*2019 -> 04/05/2019
'5_-6-*2019 -> 05/06/2019
'and so on
Of course you can change the format with
xlMDYFormat

VBA Date values when inserted to Excel cells change their format

I have date variables formatted like: 25_December_2010
Once i use
Dim strDate As String
strDate = "25_December_2010"
strDate = Replace(strDate,"_"," ")
MsgBox strDate
Surely enough a MsgBox pops up and gives me: 25 December 2010.
However once i try to put the value into a cell for example:
Sheets("Sheet1").Range("A1").Value = strdate
Instead of populating the cell with: 25 December 2010; Excel acts on it's own accord and populates the cell with the vexing entry configuration: 25-Dec-2010!
How can I have my cell populated with no hyphen characters inbetween and not having the month name trimmed?
This code puts the date into A1 in the format you write that you want:
Option Explicit
Sub WriteDate()
Dim strDate As String
strDate = "25_December_2010"
strDate = Replace(strDate, "_", " ")
MsgBox strDate
With Sheets("Sheet1").Range("A1")
.Value = strDate
.NumberFormat = "dd mmmm yyyy"
End With
End Sub
I'm not sure if it is necessary, but for clarity, since strDate is a string data type, I would probably use
.Value = CDate(strDate)
Explicitly converting it to the Date data type, before writing it to the worksheet, might be of value in non-English versions, but I've not checked that specifically.
Use a custom date format:
Sheets("Sheet1").Range("A1").NumberFormat = "dd mmmm yy" //A1 = 25 December 10
The Excel sheet is not wrong, so stop saying it is. A date is a count of the number of days since a start date. So a date is a NUMBER. You can format it how you want.
This is VBA, excel is similar though the starting dates are different.
Date variables are stored as IEEE 64-bit (8-byte) floating-point numbers that represent dates ranging from 1 January 100 to 31 December 9999 and times from 0:00:00 to 23:59:59. Any recognizable literal date values can be assigned to Date variables. Date literals must be enclosed within number signs (#), for example, #January 1, 1993# or #1 Jan 93#.
Date variables display dates according to the short date format recognized by your computer. Times display according to the time format (either 12-hour or 24-hour) recognized by your computer.
When other numeric types are converted to Date, values to the left of the decimal represent date information while values to the right of the decimal represent time. Midnight is 0 and midday is 0.5. Negative whole numbers represent dates before 30 December 1899.
Date 8 bytes January 1, 100 to December 31, 9999
This is what recording it in Excel shows.
Selection.NumberFormat = "d mm yyyy"
This works here for me
Sub DateF()
Dim strDate As String
strDate = "25_December_2010"
strDate = Replace(strDate, "_", " ")
MsgBox strDate
Worksheets("Sheet1").Range("A1").NumberFormat = "dd mm yy"
Worksheets("Sheet1").Range("A1").Value = strDate
End Sub
I also changed it from sheet. to worksheet.

Format function vba changing date

The format function in vba is changing the date. e.g for format("3/12/2009","DD/MM/YYYY"), the function returns 12/03/2009 where "3/12/2009" is what excel vba reads from a cell that has the value 12-Mar-2009 and the format as "dd-mmm-yyyy"
No it's not.
If a date-as-string is passed to the Format function, it will parse it using current regional settings. Your settings are obviously MM/DD/YYYY which is default for USA. Nothing prevents Excel from displaying a date as DD/MM/YYYY if set manually, but by default it would display MM/DD/YYYY.
To do: Stop reading dates as strings. Read them as dates.
dim d as date
d = activecell.value
Had few times problem myself where VBA in Access reades most dates as europian but some as USA:
This DOES NOT work properly:
myRs.FindFirst ("Date =#" & myDate & "#")
This works:
myRs.FindFirst ("Date =#" & Format(myDate, "Long Date") & "#")
The long date (eg 01 January 2012) clearly makes the difference between month and day