Changing date formats in Excel using - vba

I have a excel sheet in which a column has date date in the format "yyyyMMdd" and I want to format it as "yyyy/MM/dd".
For this I tried to use following line inside macro, but it's converting cell data as "###.....#" instead of changing date format.
Sheet1.Range("C3", "C302").NumberFormat = "yyyy/mm/dd"
...
result = "#####...#"
...
Can someone tell me why it's happening? Is there any other way for doing this?

If a date/time cell appears full of # signs, it means that the column is too narrow to display the format.
Make the column wider to accommodate the full width of the selected date format.
See this screenshot. Both columns have the same format. Column A is too narrow to show the dates. Column B is wide enough.
Edit after discussing in chat:
The screen shot you posted in chat is this:
The "dates" you are referring to are not dates. They are numbers that are way higher than what Excel uses for dates in this millenium.
Excel stores dates as whole numbers, starting as 1 for 1/1/1900. What you show in your screenshot are numbers way higher than Excel dates.
Your number 20150930 is NOT what Excel considers Sep-30-2015. For Excel, that date would be the number 42277, which you can perfectly format as that date.
The reason that your "dates" formatted with your format string come out as ##### is that the numbers are way higher than what Excel can interpret as dates.
You will need to convert your numbers to real Excel dates, which you can do with a simple formula. With your first "date" number in cell A1, you can use the formula
=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))
to return a value that Excel regards as a true date for Sep-30-2015 in this screenshot:
So, the reason for all the # signs is that the numbers you are trying to format as dates are too big for dates in Excel's algorithms.

With all the good answers, I will add simple vba solution...
Option Explicit
Sub FormatDate()
Dim xlRng As Range
Dim xlShtRng As Range
'//- Date format 20160112
Set xlShtRng = [A3:A10] '//- or [A3, A6, A10]
For Each xlRng In xlShtRng
xlRng.Value = DateSerial(Left(xlRng.Value, 4), Mid(xlRng.Value, 5, 2), Right(xlRng.Value, 2))
xlRng.NumberFormat = "yyyy/mm/dd" '//- 2016/01/12
Next
End Sub

Please try this..
=LEFT(A1,4)&"/"&MID(A1,5,2)&"/"&RIGHT(A1,2)

Related

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.

VBA date format code

I was wondering if there is any possibility to write a VBA code where the column A should always have a date format like this: 12.10.2017 (not 12/10/2017 or 12-10-2017). If anything else is written in the column A like "12" or "car" the entry should be deleted. It has to accept only the date format mentioned above.
I used data validation for this, with length 10 and the date format to take only "." into consideration, but I want to do it as a VBA code instead.
Thanks!
A valid date is a long representing the number of days since the 1st january 1900. So a valid date would be 45603. You can display this date in any format you wish using the format codes d, m and y . So to display the date as dd.mm.yyyy then set that numberformat in the cells in column A. Your problem though is that Excel will only accept a date entered as either a long or in a built in date format (using /, - or space as a separator). You could allow the users to enter a text string in the format dd.mm.yyyy and then convert that string into a date and then reject it if the conversion didn't result in a valid date - but wouldn't it be easier to just train your users to enter dates correctly?

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

VB.Net: Use different date format from Excel sheet while importing

From an Excel sheet I import to MSAccess database. When I read the date column from the Excel sheet, want to convert it to known date format.
I get two Excel formats, one with dd-mm-yyyy format and another with mm/dd/yyyy.
When I import Excel sheet with date 9/14/2015, I get an error message "string was not recoganized as valid date time".
timesheetDate = xlWorkSheet.Cells(1, Column).value
tempDate = Convert.ToDateTime(timesheetDate)
How to convert to two different formats of date to one format?
Usually I using the two properties: "ToOADate" and "FromOADate" when converting or moving data with no problems.
For sample: if you want to read a date from Excel to your form
Convert cell of date in Excel to number.
In form: convert the number to a date.May this short script help you:
Dim DateAsNumber As Integer
DateAsNumber = Int(Now.ToOADate)
MsgBox(DateAsNumber) 'if now is 13-Apr-2016 will you get 42473
Dim MyDate As Date
MyDate = DateTime.FromOADate(DateAsNumber)
MsgBox(MyDate) 'this will convert 42473 to 13/4/2016 or 4/13/2016 depending on your system date format.

how to get excel to treat a date as a date not a string when doing CopyFromRecordset

I have an SQL query from SQL Server which returns dates as a string in the format "YYYY-MM-DD".
If I enter a date in this format into a cell, it's recognised as a date.
But when I populate a worksheet with CopyFromRecordset, it seems to be treated as a string.
Any formula which uses the cell converts it to a date first. For example, if my dates are in col A and I make a new column B filled with a formula =A1 + 0
the formula returns my date, as a date.
The problem:
I use the Recordset data for a few things, one of them being a pivot table.
The pivot table does not see my dates as dates. I can't group as dates, for example. My hack is to make a new column which is basically =A1 + 0
I'm going to change my macro to automate this adding a zero, but I wonder if there's a way to get it right from the moment the CopyFromRecordset is performed.
The easiest way would be to do the conversion on the SQL server e.g.
SELECT CAST(date_text AS DATE) FROM TestExcelDates;
CopyFromRecordset is well known for causing data type / cell formatting issues in Excel.
I think I remember reading somewhere this is because the datatype of the recordset is ignored and Excel attempts to work out the format of each column itself based on a subset of the data in the recordset.
The best way round this is to set the cell formatting in the destination range before performing the CopyFromRecordset.
I had this problem after I had changed a view on my SQL Server database. I had changed the data type to DATE; formerly it was on an older version which didn't support DATE so I had used DATETIME. I suspect Excel doesn't always recognize the Date datatype through the SQLOLEDB provider, but it does recognize DATETIME. The field of interest is meas_date. So I altered the view by changing this to a cast SELECT CAST(meas_date AS DATETIME) AS meas_date, ... and refreshed the query in Excel. Worked!
Use the CDate() function when populating cells with dates from the recordset. This will convert the string to a date value.
Edit
That works for setting individual cell values. For using CopyFromRecordset I think you need to do the conversino in the SQL query, so the column returned by the query is a date type rather than a string.
I had this problem too importing data from Teradata, and got around it by first formatting the date columns with NumberFormat = "m/d/yy h:mm;#" (24 hr date) then stepping through the date fields afterwards with VBA and doing ws.cells(iRow, iCol).value = ws.cells(iRow, iCol).value, it forces Excel to reevaluate the string into a date/time field.
This probably will not be the answer but will surely helps you finding the right solution for your problem
String stringCellValue = myCell.toString();
here myCell has datatype as CELL which I've converted to String format.
If u want it in desired Date format, then u can try this-
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
myCellDate = sdf.parse(stringCellValue );
Hope it helps in solving your problem...