Format function vba changing date - vba

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

Related

Date value returning in a different format on the first of each month

This question is related to this one, however I thought I'd create a new post since it's not the exact same issue, and the ideas on it were just being repeated.
I have a selection formula for my Crystal Report. It's supposed to select data where the Stage field in one table is 6, and the PaymentDate field in another is less than, or equal to, the value of the DateTimePicker control.
The code that I have below is working fine for most of the dates. However, say for example I have the following data in the database:
Sales_Headers.Stage = 6
Sales_Lines.PaymentDate = 28/01/2017 (January 28th, 2017)
When choosing a date of January 26th, up to January 31st, the data is only retrieved when the date is 28th or higher. However, if I then select a date of 1st February (Or the 1st of any month to be precise), it is returning the date as 02/01/2017, or, 2nd January 2017, so the data isn't shown.
Why is it changing for only the 1st of each month? All other dates are being read correctly, as dd/MM/yyyy, but on the first, it's using the MM portion as the dd portion.
I've tried:
Dim dateTo As Date = dtpCRTo.Value.AddDays(1).Date
dateTo = Format(dateTo, "dd/MM/yyyy")
If cmbCRSupplier.Value = "" Then
selectionFormula = "{Sales_Headers.Stage} = '6' AND {Sales_Lines.PaymentDate} < #" & dateTo & "#"
Then I tried this in the form_Load event, as well as in the Value_Changed event of the DateTimePicker:
Dim dateFormat As String
dt.Format = DateTimePickerFormat.Custom
dt.CustomFormat = "dd/MM/yyyy"
dateFormat = dt.Text
The final thing I tried was just to have no formatting code, and just using:
If cmbCRSupplier.Value = "" Then
selectionformula = "{Sales_Headers.Stage} = '6' AND {Sales_Lines.PaymentDate} <= #" & dtpCRTo.Value.Date & "#"
But it was the same result for all of them.
As well as the method #Siva was talking about (Always a good way, that way you can create the formula there and use the syntax that it's looking for), there is the way you're trying, to do it in VB.NET.
As I just mentioned, the syntax is important, and this is what is causing your issue.
I've not seen anyone try to use DateTimes in this method before, using `#value#.
The correct way to format dates into a RecordSelectionFormula (again, this is something you'll have seen if you'd have created it in Crystal itself), is to DATE(yyyy, MM, dd).
So, the correct way to syntax this is to use:
selectionFormula = "{Sales_Headers.Stage} = '6' AND {Sales_Lines.PaymentDate} <= DATE(" & _
dtpCRTo.Value.Date.Year & "," & dtpCRTo.Value.Date.Month & "," & dtpCRTo.Value.Date.Day & ")"
Use this method to insert your dates into selection formulas in the future, that way you can't get it wrong.
If this doesn't work, then you need to check your Region and Local Date/Time settings in Control Panel, to ensure they're set correctly.

Comparing US date to UK date

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

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.

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.