将.csv文件导入Excel并使用VBA重新格式化日期列

时间:2014-05-19 18:52:33

标签: vba excel-vba excel

previous question中,我询问了使用VBA使用Excel导入.csv文件的方法。我收到了有关使用VBA打开.csv文件的有用答案,但我担心使用此方法会导致日期格式问题as a commenter on another of my questions mentioned。考虑到这一点,是否有类似于Dan用于导入文件的方法?我知道录制的宏通常很笨拙,所以我想知道下面的标准代码会有什么改进。

With ActiveSheet.QueryTables.Add(Connection:= _
    "FAKENAME.csv" _
    , Destination:=Range("$A$1"))
    .CommandType = 0
    .Name = "FAKENAME"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 65001
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 _
    , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With

更新:

如果我选择不导入日期,则会出现这样的问题:

     DateTime               Format

     05/11/2014 3:22        Custom
4/27/2014 9:53:01 AM        General
     11/22/2013 8:29:35 AM  Custom
     05/11/2014 8:26        Custom
1/17/2014 12:28:24 PM       General
     05/11/2014 3:22        Custom

虽然我可以在导入时解决此问题,但如果我只是打开文件,尝试手动更改整列的日期格式,实际上并不会更改格式。

1 个答案:

答案 0 :(得分:1)

我也不太可能使用这种QueryTables方法,正如@ Dan-Wagner在你之前的帖子中提到的那样。我会使用Microsoft Scripting Runtime库中的Text Stream对象解析文件。您将不得不将其添加为参考(工具 - >参考文献+从列表中查找并选择它)请参阅下面的一些如何使用它的示例:

Dim fileSys as New FileSystemObject 'the New keyword is important here!
Dim TS as TextStream
Dim txt as String, sp() as String   'first one is one string, second is an Array
Dim i as Integer

Set TS = fileSys.OpenTextFile("C:\myinputfile.csv")
i = 1
Do While Not TS.AtEndOfStream
    txt = TS.ReadLine               'Read one whole line of data
    sp = Split(txt, ",")            'Split by commas into "Cells" (kinda)
    Sheets(2).Cells(i, 1) = sp(0)     'Note, sp() is "Zero-Based" but ranges are 1 based
    Sheets(2).Cells(i, 2) = sp(1)     'So you'll always access sp onelower than myOutputRange
    '
    '
    '
    i = i + 1
Loop

请注意,我已将您的输出分配给第二个工作表,但您可以在此处使用任何范围。

MSDN TextStream对象:http://msdn.microsoft.com/en-us/library/aa242724%28v=vs.60%29.aspx 引用库:How do I use FileSystemObject in VBA?

希望这有帮助!