将文本文件转换为excel时如何修复日期格式?

时间:2014-11-26 12:13:15

标签: excel vba xls

我使用amacro将txt文件转换为xls,但我遇到的问题是日期字段没有以正确的格式转换。例如,我的日期为4/11/2014 (dd/mm/yyyy),当文件转换为xls时,我的日期显示为:11/4/2014.

我该如何解决?

代码:

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

1 个答案:

答案 0 :(得分:1)

您可以在这里使用两种方法,简短的方法 - 并不总是有效 - 或者很长的方式,这将有效,但需要一段时间才能运行。

简短的方法:

Columns("E, H, S, V, AB, AF, AJ, AL, AO, AS, AY, BE, BH").EntireColumn.NumberFormat = "dd/mm/yyyy"

漫长的道路:

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