Comparing US date to UK date - vba

I'm using Excel VBA and want to verify 2 dates are the same. On my macro, the user enters a date in the mm/dd/yy format (01/31/15). When the macro runs, it opens a file submitted by a user in Europe. On that sheet, there is a date field where the date is entered in the dd/mm/yy format (31/01/15). I'm wondering if there is an easy way to compare these 2 dates to verify that they are the same.
I could convert one of the dates into the other format and then convert both to a date serical to see if they are the same. I wanted to check and see if there was an easier way or a function that could do that.
Thanks for the help........

So apparently the MSDN Library has a converter Sub:
Function MakeUSDate(DateIn As Variant) As String
' Do nothing if the value is not a date.
If Not IsDate(DateIn) Then Exit Function
' Convert the date to a U.S. Date format.
MakeUSDate = "#" & Month(DateIn) & "/" & Day(DateIn) & "/" & Year(DateIn) & "#"
End Function

Related

Trying to make a Collection of Dates from concatenated Strings

I am making a macro where I search through a spreadsheet of dates where each component of a date is already broken into separate components ie, year, month, day, hour, minute, second.
I want to compare these dates and find the earliest and latest date.
I was trying to concatenate the date components from strings into a Date variable, store the Dates in a Collection, and then search the Collection for the earliest and latest dates.
Dim dt As Date
Dim dtstring As String
Dim dates As New Collection
... [code where I just set unrelated variable values from cells and started a loop]
dtstring = "#" & day & "/" & month & "/" & year & " " & hour & ":" & minute & ":" & second & "#"
dt = dtstring
dates.Add dt 'add a Date into the dates collection
It doesn't like setting my Date variable value, dt, from a string but every example I find of this hard codes the Date variable with something similar to
Dim dteAppointment As Date = #8/2/2007 14:02:00#
whereas I need it set by the six date components.
Any help on this is much appreciated.
Under presumption you still have the original dates available, simply use:
Application.WorksheetFunction.Max(<Range>)
and
Application.WorksheetFunction.Min(<Range>)
respectively.
This will already return the result for you, without needing to do any crazy string formatting and what not.
EDIT: Probably worth noting, the returned value is Double type. It's not that big of a deal, given the function automatically serializes the input dates, but if you're returning the result to a variable, make sure to return it to a Dim resAs Double and not As Date
Afterwards, if you wish to return it back to a specific cell or somewhere as a Date, simply use the inbuilt DateSerial() in-built method! ;)

using string values for DATE criterias for COUNTIF in vba excel

I have 2 cells in Range B:B, which I wish to apply countif formula to via VBA in Excel.
27/09/2017
13/06/2018
I have tried
MsgBox (WorksheetFunction.CountIf(Range("B:B"), "27/09/2017"))
This returns 0
MsgBox (WorksheetFunction.CountIf(Range("B:B"), CDate("27/09/2017")))
This returns 1
I am trying to figure out how I can get the macro to return both date values, via
MsgBox (WorksheetFunction.CountIf(Range("B:B"), "<=" & CDate("13/06/2018")))
However this returns 0
This seems to indicate that I do not quite understand how to filter dates in countif via strings. Would it be possible to share a alternative?
I hope to implement a text input box where the user can input a date string which then applies the countif on
You need to convert the date into a double first to compare the actual value of the date independent from the format.
"<=" & CDbl(CDate("13/06/2018"))
Why is this?
If you concatenate a string with a date like in "<=" & CDate("13/06/2018") the date is converted into a string and the result is "<=13/06/2018" (here the date is a string not a value).
If you convert the date into a double CDbl(CDate("13/06/2018") the result is 43264 which is the serial number that represents the date.
Dates in Excel are stored as serial numbers counting from 1900-01-01 so 2018-06-13 is day 43264 since 1900-01-01.
So with "<=" & CDbl(CDate("13/06/2018")) you actually compare the cell value to "<=43264". So you compare to a value and not a text. This works because if a cell is formatted as date Excel actually stores the serial value but shows the formatted string for user compatibility.
Conclusion
If you want to compare dates always compare their values not their strings.
Also see: How to use dates and times in Excel.

Change date's format after loading it to UserForm textbox

I have a userform with textbox. When textbox is initialized it's getting filled with actual date. What I want to do is to fill it with custom date format = DD-MM-YYYY
I wrote code below and something is wrong about it but I have no idea what is wrong. Code has msgbox before inserting value, MsgBox shows date in a custom format but when it is passed to textbox.value it's like M/DD/YYY.
Dim year As Long, year_control As Date
year = Format(Date, "yyyy")
year_control = Format(Date, "dd-mm-yyyy")
MsgBox (year_control)
textbox.Value = year_control
(...)
If year_control < "01-04-" & year Then
Me.Controls("rok1").Value = True
Else
Me.Controls("rok2").Value = True
End If
You cannot "Format" a date variable:
year_control As Date
year_control = Format(Date, "dd-mm-yyyy")
The above code does nothing because a Date variable is simply holing a date more specifically VBA stores Date variables 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.
No matter what you do to this variable it will always 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.
So while you can change the internal value that is held by the Date Variable you cannot store its format inside of the same vairable.
You can however display it however you would like inside of a string variable. So, if you used:
Dim year As Long, year_control As Date
Dim strYear_control As string
year = Format(Date, "yyyy")
year_control = Format(Date, "dd-mm-yyyy")
strYear_control = Format(year_control , "dd-mm-yyyy")
MsgBox (strYear_control)
textbox.Value = strYear_control
It should work as you are expecting. As the Format() function will return a Variant (String) containing an expression formatted according to instructions contained in a format expression.
As a side note you may also wish to use
Format$(year_control , "dd-mm-yyyy")
as it will be much faster, You also can use FormatDateTime to format your date in other various ways.

convert date in excel from dd-mm-yyyy to dd/mm/yyyy format and to check whether a date is valid or not

I'm having a hard time in converting the date from dd-mm-yyyy format to dd/mm/yyyy format.
For Example,
When i enter a date in excel as 25/02/2012 (dd/mm/yyyy), after entering the date if go in the next line it converts the date in the 25-02-2012 (dd-mm-yyyy) format.
what i want to do is that when i enter the date in (dd/mm/yyyy) format in excel it should keep it as it is and should not change it back to (dd-mm-yyyy) format when i go the next cell.
when i enter my date as the current system date my code gives me an error, i am having trouble validating the date i.e. is the date entered is a valid date or not
Sub valid_date()
' ---------------------------------------------------------------------
' Final Code - Trial
' ---------------------------------------------------------------------
Dim d1 As Variant
Dim IssueDate As Variant
Dim str As Variant
d1 = Worksheets("Sheet1").Cells(6, 1).value
MsgBox " The Issue Date format is " & d1
sysdate = Date
MsgBox "System Date is " & sysdate
If IsDateValid(d1) Then ' if date is in dd/mm/yyyy format then print this
If (d1 > sysdate) Then
MsgBox "Invalid date"
End If
End If
End Sub
Function IsDateValid(pdate) As Boolean
IsDateValid = False
Set RegExp = CreateObject("VBScript.RegExp")
' it only matches whether date is in dd/mm/yyyy format or not
'
' [1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1] ---> it allows the DATE from 01 to 31
' [1-9]|0[1-9]|1[0-2] ---> it allows the MONTH from 01 to 12
' 1[9][0-9][0-9]|2[0][0-9][0-9] ---> it allows the YEAR from 1900 to 2099
'
' below is the regular expression for checking the date in dd/mm/yyyy format
RegExp.Pattern = "^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[/]([1-9]|0[1-9]|1[0-2])[/](1[9][0-9][0-9]|2[0][0-9][0-9])$"
' check whether the date is in dd/mm/yyyy format or not....
tempdate = RegExp.Test(pdate)
If tempdate Then ' if tempdate is in dd/mm/yyyy format than proceed further
'If isdate(tempdate) Then ' if date is a valid date then proceed further
If isdate(pdate) Then
IsDateValid = True
Else
IsDateValid = False
End If
Else
IsDateValid = False
End If
End Function
i'm using the above mentioned code by using a regular expression to check whether the date is in dd/mm/yyyy format or not
but the problem which i'm facing is that it takes the date in excel as dd-mm-yyyy format whenever i enter the date in dd/mm/yyyy format.
i have updated my code a bit,
i also need one more help when i enter my date as the current system date it gives me error
for example,
when i enter my date as 09/09/2012 (suppose this your current system date) and when i check this date using IsDate method, it gives me an error
i have again edited my code,
Can anyone please help me on this
You don't need VBA/RegEx. Select the cells/columns where you input dates and create a Custom number format: dd/mm/yyyy. Now no matter how you type in a valid date (05-05-2000, 3-1-2010, 14/6-1990, etc.), it should be formatted as dd/mm/yyyy.
And, as Olle points out, you should use the Date object rather than Variant if you are going to be manipulating dates in VBA. This way you're working with the serial number and not a string with potential formatting issues.
First, I suggest you check the regional settings for dates on your computer. If you set it to use the "dd/mm/yyyy" format it will be used by Excel as well and hopefully remove the need for any RegEx VBA-code.
Second, if you do need to use VBA to reformat dates, I strongly suggest you use the Date data type instead of Variants. I also advise you to use Option Explicit at the top of your code and explicitly declare any variables in order to minimize typos and produce better quality code.
Third, I've looked through your code some more and it seems it will never work:
1. Because it is never declared, tempdate is a Variant
2. You assign tempdate to be a boolean, from the result of RegExp.Test(pdate)
3. So when you check IsDate(tempdate) it will always be false, since a boolean can never be a Date.
Again, if you use the Date data type, you can skip the RegEx... :)
I use Adobe online PDF to Excel and dates display correctly as MM/DD/YYYY but when extracting month (=Month()) it returns the DD portion. It is being interpreted as DD/MM/YYYY. I saved the file as a .csv closed and restarted excel and opened the .csv file and the dates were correct MM/DD/YYYY.

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