I am reading data from a CSV file into a Sql table. Problem is some dates in a date column in the CSV would be empty. I am using the following code to convert the empty cells to NULL values. However I get the following error :Additional information: String was not recognized as a valid DateTime.Couldn't store in ANALISEDATUM Column. Expected type is DateTime
My code is :
Do Until parser.EndOfData = True
Dim data As String() = parser.ReadFields()
For i As Integer = 0 To data.Length - 1
If (String.IsNullOrEmpty(data(i))) Then
data(i) = DBNull.Value.ToString
End If
Next
datatabel.Rows.Add(data)
The error occurs at the last line.
Regards
I think, seems the format of the date adding to the table is wrong, please make sure the format of the table date column and csv file date value are same.
Ex: Table date format might be : mm/dd/yyyy
csv file date value format might be : dd/mm/yyyy
Related
Thanks to all those who have helped thus far and helped me refine the problem
I'm receiving a CSV file from a third party software application with date time stamp in UK format that can be read by the VBA as a US date format
My machines "Region and Language Settings" are set to English (United Kingdom) but if I use
Application.LanguageSettings.LanguageID(msoLanguageIDUI)
The result is 1033 - ie: English, US and not fitting my machine settings.
CSV is a file with columns as follows:
| report name | value | % | date |
CSV created by a program and saved by users - a direct save of the CSV to disk by the third party app results in CSV table rows as follows:
"Report name","264","2.2 %","08 Jul 2021 11:05" (this imports correctly)
If users open the CSV and then save from Excel the file is saved as follows (note no quotation marks and amended date format:
Report name,1,0.00%,01/07/2021 12:37 (this fails to import correctly - cell read by VBA as 7th Jan 21)
My code should be able to handle both situations.
I'm importing the CSV data as follows:
Set csvWB = Workbooks.Open(my_FileName)
Set csvData = csvWB.Worksheets(1)
Dim csvReportAr() As Variant 'array of reprot names from column one of the CSV
Dim csvNumberAr() As Variant 'array of values (report results) from col 2 of the CSV
Dim csvDateAr() As Date 'array of the dates the reports were run
Do While csvData.Cells(cellRow, 1).Value <> Empty
Do While csvData.Cells(cellRow, 1).Value <> Empty
ReDim Preserve csvReportAr(cellRow)
ReDim Preserve csvNumberAr(cellRow)
ReDim Preserve csvDateAr(cellRow)
csvReportAr(cellRow - 1) = csvData.Cells(cellRow, 1).Value
csvNumberAr(cellRow - 1) = csvData.Cells(cellRow, 2).Value
Debug.Print "cell value = " & csvData.Cells(cellRow, 4).Value
Debug.Print "Month (of cell value) = " & Month(csvDateAr(cellRow - 1))
csvDateAr(cellRow - 1) = convertDateUKtoUS(csvData.Cells(cellRow, 4).Value)
Debug.Print "Date value = " & csvDateAr(cellRow - 1)
Debug.Print "Month of date = " & Month(csvDateAr(cellRow - 1))
cellRow = cellRow + 1
Loop
the debug statements print the following:
cell value = 07/01/2021 06:45:00
Month (of cell value) = 12
Date value = 07/01/2021
The difficulty is that the date I'm trying to import here is listed as 01/07/2021 06:45:00 in the CSV (1st July) based on the text editor view of the CSV. Just reading this cell value it seems that the VBA assumes this is a date and stores as a date saved in US format.
I suspect this is a locale issue? My locale settings seem incongruous and other users might have erroneous locale settings as well so we should be able to account for this
Questions:
Can I force VBA to read the date-time stamp as a string and then parse manually to ensure read as date in UK format? - OR - Can I read as a date time stamp specifying a specific format to read with?
Can you advise on the issue with locale with VBA stating locale is English US whilst machine settings seem to be English UK?
Can I change the locale with VBA temporarily? (other posts I've read suggests this is not advised!)
Is my use of cell.value inappropriate?
Rest of post deleted as probably no longer relevant
Thanks to all contributors so far!
I have partial but inelegant solution - I hope others can do better than me. I still can't work out why the UK date is being parsed to a US date automatically.
Thanks to all for their help as I could not have got my project to work without your helpful comments.
My partial solution:
Read the data from the CSV, assuming it may have been parsed incorrectly
If day(importDate) <=12 we are at risk of erroneous date import
create an alternate date with transposed days /months from the importDate
Use a vbYesNo MsgBox to get user to confirm which date is correct.
This works for my project as all dates in the single CSV file should be equal, You could use a similar solution of error checking a date for being read in US vs UK format if all dates in your CSV where recorded in the same format. However it will not help others who want to processes multiple CSVs or who may have a CSV with different date formats in it.
An alternative approach would be to read the csv file into an array using a CSV parser that lets you specify the file's date format, and then paste the array into a worksheet.
Here's such a parser (I'm the author):
https://github.com/PGS62/VBA-CSV
In this example, Data is pasted to a new worksheet.
Sub Demo()
Dim Data As Variant
Dim Target As Range
Data = CSVRead("c:\temp\datesukformat.csv", _
ConvertTypes:=True, _
Delimiter:=",", _
DateFormat:="D/M/Y")
Set Target = Application.Workbooks.Add.Worksheets(1).Cells(1, 1).Resize(UBound(Data, 1), UBound(Data, 2))
Target.value = Data
End Sub
I try to get a value from excel and to use in vb.bet but when i try to convert date from Excel my vba display error.
I try this:
Dim Target As DateTime = Nothing
Target = DateTime.ParseExact(currentWorksheet.Cells(CurrentRow, 19).Text, "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture)
This code currentWorksheet.Cells(CurrentRow, 19).Text get me 3939344687 value from Excel, my date in excel are 01/26/17.
When i try to convert this number to date i get error.
Another code what i try are :
Target = Convert.ToDateTime(currentWorksheet.Cells(CurrentRow, 19).Text)
But doesn't work.
I AM FACING ONE PROBLEM.
I AM USING BELOW METHOD FOR MAKING STRING VALUE TO DATE.
string values is like this ="01/12/2002" like "dd/MM/YYYY"
My problem is that.
two string values
->1)01/01/2025
->2)1/1/2025
i am getting the Value like above 1 or 2
Dim d As Date = DateTime.ParseExact(dumm, "dd/MM/yyyy", Nothing)
if 1 comes nothing will happen but
if i get 2 i am facing error like String was not recognized as a valid DateTime.
As per my Analysts what i understood is date should be 2 digits Remaining all are two digits other wise giving the error.
but some times i am getting single digits from the excel to vb.net
how can i solve this issue...
Dim dumm As String = DtSet3.Tables(0).Rows(k + 0).Item(3).ToString
Dim d As Date = DateTime.ParseExact(dumm, "d/M/yyyy", Nothing)
i put the break point on dumm ok dumm vlaues= "1/2/2026 12:00:00 Am"
Error...............
now
Dim dumm As String = DtSet3.Tables(0).Rows(k + 0).Item(3).ToString
Dim d As Date = DateTime.ParseExact("01/02/2026", "dd/MM/yyyy", Nothing)
Working Fine.......
Use the date format string "d/M/yyyy h:m:s tt". This will handle both cases i.e. with and without leading zero for the day and month. Additionally, since your actual variable has a time component in addition to the date, you need to add the format string for parsing time as well.
However, I would advise you to use TryParseExact, which will return boolean values based on success or failure of the parse rather than throwing exceptions.
Demo for using TryParseExact along with appropriate format string.
I have created a DataGridView and I add columns to it like this:
Dim col_1 = New DataGridViewTextBoxColumn
col_1.Name = "Date"
col_1.DefaultCellStyle.Format = "MM/dd/yyyy"
data_grid.Columns.Add(col_1)
then I add data to the column like this:
data_grid.Item(1,1).Value = temp_date
The grid is filled with the correct data and everything works, however...when I click on the column headers, the column that shows the dates does not sort correctly (it sorts alphabetically) and I know this is because I set it up as "DataGridViewTextBoxColumn", but there is no option for a date type column. So how to I set it up as a date column so it sorts based on the date when the header is clicked?
Thanks.
You should also set the ValueType of the column:
DataGridView1.Columns(0).ValueType = GetType(Date)
Then convert date_temp to a Date-value before assigning this to the cell's Value.
Using CDate could be your first attempt:
data_grid.Item(1,1).Value = CDate(temp_date)
otherwise, investigate Parse, TryParse or Convert, to obtain the date-value.
I have set a specific format for a column in an Ultragrid. But still the DateTime is in its default format.
//Code
UltraGridColumn.Header.ToolTipText = Field.FieldDescription
UltraGridColumn.Format = "d"
Even after the above format is set the grid shows the value in the column as 06/06/2013 02:43PM
But the expected output is 06/06/2013
Why i'm getting this?
Added the column style as DateTime.
//Code
UltraGridColumn.Style = ColumnStyle.DateTime