【发布时间】:2015-07-31 22:04:37
【问题描述】:
SQL Server datetime 值在 CSV 文件中表示为 2015-01-29 19:23:00.000(例如)。
不幸的是,VBA 的IsDate 函数在 Excel 宏中对其进行评估时不会将其识别为有效日期(我猜是因为小数秒)。 DateValue 也无法转换值。
是否有一个 VBA 调整来使这项工作,或者我需要去除小数秒?
** 编辑 **
更复杂的是,ActiveCell.Value 将文本值(例如 2015-05-20 15:31:30.000)转换为小数(例如 42144.4166666667)。因此,Evaluate 技巧将不起作用。
为了更好地说明情况,下面是代码:
'
' format a CSV file for better readability
'
Sub FormatCSV
' move top-left corner
Range("A2").Select
' while the current cell's value is not empty
Do While Not IsEmpty(ActiveCell)
' 2015-05-20 15:31:30.000 => 42144.4166666667
Debug.Print ActiveCell.Value
' if the cell contains a date
If IsDate(ActiveCell) Then
' format entire column as date/time
ActiveCell.EntireColumn.NumberFormat = "mm/dd/yy hh:mm"
End If
' resize
ActiveCell.EntireColumn.AutoFit
' move a column to the right
ActiveCell.Offset(0, 1).Select
Loop
' move top-left corner
Range("A2").Select
End Sub
【问题讨论】:
-
很有趣,因为
Evaluate("=DateValue(""2015-01-29 19:23:00.000"")")有效
标签: sql-server vba excel datetime