VBA:Compare two date formats in vba - vba

How do we compare two date strings in vba, like "01.02.2013 < 02/02/2013"?
Whatever the dates are this always showing true. And two date formats are correct in the example i menioned.
Below vba code throws error.
Sub aa()
Dim a As Variant, b As Variant, c As Variant
a = Format("1.2.2012", "DD\/MM\/YYYY")
b = Format("2.2.2012", "DD\/MM\/YYYY")
MsgBox (a)
End Sub

Convert your dates (strings) to a format CDate() accepts. 02/02/2013 works, I think 02.02.2013 doesn't. Use Replace() if needed.
Then you can cast your String data into the Date datatype with CDate(myString). Dates can be compared with each other by the means of the usual operators, such as > < =.

Clean up the strings to the correct format (see what CDATE accepts, and then use CDate(a) >= CDate(b) to compare.

Related

My Format Date Function Doesn't Work In Microsoft Access

I am writing a simple code that converts the date value of the default format(MM/DD/YYYY) of the first textbox into a different format of(DD/MM/YYYY) of the second textbox based on the Exit Event
For some reason, it ALWAYS returns the date format MM/DD/YYYY.
'First Code to convert it into a string
Private Sub date1_Exit(Cancel As Integer)
Dim dat_ed As Date
dat_ed = CDate(Me.date1.Value)
dat_ed = Format(CStr(dat_ed), "d/m/yyyy")
Me.date2.Value = dat_ed
End Sub
'Second Attempt to convert it directly
Dim dat_ed As Date
dat_ed = CDate(Me.date1.Value)
dat_ed = Format(dat_ed, "d/m/yyyy")
Me.date2.Value = dat_ed
Your code is wrong on a couple of places, mainly because you're confusing dates and strings formatted as dates.
Dim dat_ed As String 'You want this to hold a formatted date, so it's a string not a date
'dat_ed = CDate(Me.date1.Value) 'We can't do this because a string can't hold a date
'So we combine the next two calls
dat_ed = Format(CDate(Me.date1.Value), "d/m/yyyy")
'No CString in format, we need it to get the date as a date
'Note that / in format means the system date separator, if you want literal slashes, use \/ instead
Me.date2.Value = dat_ed
Also note, if your textbox has the Format property set to a specific date format, you need to modify that property, instead of assigning a formatted date to it.
You are making it way too complicated.
First, if you have applied a date/time format to the Format property of a textbox, Access knows that this is a datetime value.
Second, a date/time value carries no format. It is a value.
Third, to have a date value displayed in a specific format, apply this format to the Format property of the textbox.
Thus, apply the format d/m/yyyy (or d\/m\/yyyy) to textbox date2. Then:
Private Sub date1_Exit(Cancel As Integer)
Me!date2.Value = Me!date1.Value
End Sub

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.

Vbscript How to find what is give date format?

I want to know what is the format of given date in vbscript?
Example
If the date is 10/08/2015 I want to check whether which format it its?
dd/mm/yyyy or dd/mm/yy
I check so many function is vbs nothing fit for my requirement
The following function might be useful in some situations. It can distinguish between dd/mm/yyyy and mm/dd/yyyy when possible and tells you when not. It does no error checking so would give misleading results if the string is anything other than a valid date in one of those two formats:
Function FormatUsed(dateString)
Dim parts, first, second
parts = Split(dateString, "/")
first = CInt(parts(0))
second = CInt(parts(1))
If first > 12 Then
FormatUsed = "dd/mm/yyyy"
ElseIf second > 12 Then
FormatUsed = "mm/dd/yyyy"
Else
FormatUsed = "??/??/yyyy"
End If
End Function

How to change date format vb.net 2015

I want to filter SQL-table between start date and end date, I used before string variable then I use string.format to make the format mm/dd/yyyy, I tried now in VB.net 2015 the following code:
Dim S as String
s=inputbox("Enter Start date")
S=string.format(S,"mm/dd/yyyy")
But it doesn't work, can somebody give me a solution?
You could try this for handling the input value, assuming you only need the date value as a formatted string, since your question is about formatting a date:
Dim S As String
S = InputBox("Enter Start date")
If IsDate(S) = True Then
Dim d As Date = Date.Parse(S)
S = d.ToString("mm/dd/yyyy")
Else
'Handle the non date input here
End If
But I think you should consider #Plutonix comment, since we don't know exactly how you are sending the date to perform the filtering, or how your table fields are defined.
Regards!

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.