【发布时间】:2014-05-19 18:52:32
【问题描述】:
在previous question 中,我询问了一种使用 Excel 使用 VBA 导入 .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
虽然这可以在我导入时解决,但如果我只是打开文件尝试手动更改整个列的日期格式实际上并不会更改格式。
【问题讨论】:
-
CSV 中的日期格式是否一致?还是您的宏需要先弄清楚日期格式?
-
@CodeJockey 它们都是 MDY 格式,有些还包含时间。我不认为将他们都视为有时间的问题,不是吗?
-
我之前曾与讨厌的日期纠缠不清,但不可否认的是,我最终还是使用了 ruby 来清理 CSV。您能否通过一些示例向我们展示 MDY 字段的外观?
-
@Dan 当然,当我在导入期间也未能更改日期时,我会告诉你最终的错误是什么。