i'm using vba from foo.xlsm file, to open bar.csv file then copy it to the foo.xlsm file. however, surprisingly, it turns out that it will mess up with the date format, sometimes recognize as mm/dd/yyyy, sometims dd/mm/yyyy.
The csv file has a row like this:
"USD/MYR","TRF:1234","20/04/2017","01/06/2017","11/09/2017","01/06/2017"
, so all the dates are in dd/mm/yyyy format.
If I open bar.csv file manually, the 4 dates are shown correctly, as
20/4/2017 1/6/2017 11/9/2017 1/6/2017
However, if from foo.xlsm using vba to open bar.csv file, it turns out to be
20/04/2017 6/1/2017 9/11/2017 6/1/2017
, and hence later copied to foo.xlsm wrong dates.
It seems excel is tring to interprete the dates as mm/dd/yyyy first, only if that doesn't work, it'll read it as dd/mm/yyyy.
The vba code is like this:
Sub import_via_excel(source_file As String, source_sheet As String, target_sheet As String)
On Error GoTo ErrHandler
Application.ScreenUpdating = False
Set wbThis = ActiveWorkbook
Dim dest_sheet As Worksheet
Set dest_sheet = wbThis.Sheets(target_sheet)
Dim src_book As Workbook
Set src_book = Workbooks.Open(source_file, True, True) ' Open in "ReadOnly" mode
Dim src_sheet As Worksheet
Set src_sheet = src_book.Sheets(source_sheet)
src_sheet.Activate
last_col = ActiveSheet.UsedRange.Columns.Count
last_row = ActiveSheet.UsedRange.Rows.Count
Dim row As Integer ' row counter.
Dim col As Integer ' col counter.
Dim src_data As String
For row = 1 To last_row
For col = 1 To last_col
src_data = src_sheet.Cells(row, col).Value
dest_sheet.Cells(row, col).Value = src_data
Next col
Next row
src_book.Close False ' close file without saving (FALSE)
Set src_book = Nothing
wbThis.Activate
ErrHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
What could went wrong?