This is my first question here, so I hope everything is correct. I’ve hacked a bit of code to read from excel and output a CSV with speech marks for every cell, blank or not. The problem is with the dates where excel converts a YYYY-MM-DD date to MM-DD-YYYY when it writes it to the CSV. To get around this I’ve written the following if statement:
If IsDate(Cells(r, c)) Then
Unfortunately the program now interprets a cell with “2A” in it as a date as well (even though I’ve checked the format in excel is text), exporting this as “1899-12-30”. I’ve put in a very quick and dirty clause to filter this
If Selection.Cells(r, c) = "2A" Then
But I was wondering if there was a more elegant way, to convert date formats that are only in the YYYY-MM-DD or similar format. And why it thinks A2 is a date!? Full code is below:
For r = 1 To Selection.Rows.Count
s = """"
c = 1
For c = 1 To Selection.Columns.Count
If IsDate(Selection.Cells(r, c)) Then
'ridiculous clause to get rid of A2 being treated as a date
If Selection.Cells(r, c) = "2A" Then
s = s & Selection.Cells(r, c)
Else
s = s & Format(Selection.Cells(r, c), "YYYY-MM-DD")
End If
Else
s = s & Selection.Cells(r, c)
End If
If c = Selection.Columns.Count Then
s = s & """" 'end of row
Else
s = s & """,""" 'mid row
End If
Next c
a.writeline s
Next r
The problem arises because
2Ais interpreted as2 AM:Dealing with this depends on what types of values are in the column alongside the dates, you could check their length or check for the default date that’s used when a DateTime contains no date part;
or look at its pattern;
if isdate(x) and x like "####-##-##"or you could convert the value to a date and check that it falls within an appropriate range.
You could also reformat the column itself
Selection.NumberFormat = "yyyy-mm-dd".