Reputation: 23
I use amacro
to convert txt files into xls
but I have the problem that the fields with dates are not converting in the right format. For example I have the date 4/11/2014
(dd/mm/yyyy)
and when the file is converted into xls
, I have the date shown like this :11/4/2014.
How can I fix it?
code:
Public Sub Read_TXT()
Dim Dir_p As String, File_to_Open As String
Dir_p = ActiveWorkbook.path
File_to_Open = Dir(Dir_p & "\")
While File_to_Open <> ""
If InStr(1, Right(File_to_Open, 3), "txt", vbTextCompare) <> 0 Then
Workbooks.OpenText Filename:=Dir_p & "\" & File_to_Open, _
Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
Comma:=False, Space:=False, Other:=False, _
TrailingMinusNumbers:=True
ActiveWorkbook.SaveAs Filename:=Dir_p & "\" & Left(File_to_Open, Len(File_to_Open) - 3) & "xlsx" _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
ActiveWorkbook.Close
End If
File_to_Open = Dir
Wend
End Sub
Upvotes: 0
Views: 825
Reputation: 17647
There's two methods that you can use here, the short way - which doesn't always work - or the long way, which will work, but will take a while to run.
The short way:
Columns("E, H, S, V, AB, AF, AJ, AL, AO, AS, AY, BE, BH").EntireColumn.NumberFormat = "dd/mm/yyyy"
The long way:
Dim bigRange As Range, rCell As Range
'// If your data has headers, change the 1 to a 2 in all the lines below.
Set bigRange = Union(Range("E1", Range("E" & Rows.Count).End(xlUp)), _
Range("H1", Range("H" & Rows.Count).End(xlUp)), _
Range("S1", Range("S" & Rows.Count).End(xlUp)), _
Range("V1", Range("V" & Rows.Count).End(xlUp)), _
Range("AB1", Range("AB" & Rows.Count).End(xlUp)), _
Range("AF1", Range("AF" & Rows.Count).End(xlUp)), _
Range("AJ1", Range("AJ" & Rows.Count).End(xlUp)), _
Range("AL1", Range("AL" & Rows.Count).End(xlUp)), _
Range("AO1", Range("AO" & Rows.Count).End(xlUp)), _
Range("AS1", Range("AS" & Rows.Count).End(xlUp)), _
Range("AY1", Range("AY" & Rows.Count).End(xlUp)), _
Range("BE1", Range("BE" & Rows.Count).End(xlUp)), _
Range("BH1", Range("BH" & Rows.Count).End(xlUp)))
For Each rCell In bigRange.Cells
With rCell
.Value = Format(CDate(.Value2), "dd/mm/yyyy")
End With
Next rCell
Upvotes: 1