Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

excel

vba

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.

like image 439
Tim Richardson Avatar asked Apr 27 '12 06:04

Tim Richardson


People also ask

How do you get Excel to recognize a date as a date?

Choose the dates in which you are getting the Excel not recognizing date format issue. From your keyboard press CTRL+H This will open the find and replace dialog box on your screen. Now in the 'Find what' field put a decimal, and in the 'replace' field put a forward slash. Tap the 'Replace All' option.

Why are dates not formatting correctly in Excel?

Imported Dates Are Text Data Although the entries in column C look like dates, Excel sees them as text, not real dates. And that's why the imported dates won't change format -- Excel will not apply number formatting to text.


2 Answers

The easiest way would be to do the conversion on the SQL server e.g.

SELECT CAST(date_text AS DATE) FROM TestExcelDates;
like image 115
onedaywhen Avatar answered Nov 15 '22 08:11

onedaywhen


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.

like image 39
markblandford Avatar answered Nov 15 '22 09:11

markblandford