【问题标题】:SQL Server datetime not recognized by VBA's IsDate functionVBA 的 IsDate 函数无法识别 SQL Server 日期时间
【发布时间】: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


【解决方案1】:

似乎 VBA 不喜欢日期字符串中的小数时间。

您可以执行以下操作之一:

  1. 去掉你已经记下的小数时间。
  2. 或者你可以用CDate(Evaluate("=DateValue(""2015-01-29 19:23:00.000"")"))包裹它

这是一个 samble VBA Sub:

Sub Macro1()
    Dim d As String
    Dim v As Variant
    d = "2015-01-29 19:23:00.000"
    v = CDate(Evaluate("=DateValue(""" + d + """)"))
    Debug.Print IsDate(v)
    Debug.Print v
End Sub

打印出来:

正确
2015 年 1 月 29 日

【讨论】:

    【解决方案2】:

    @chancea 的帖子相同,但有一些不同

    Sub test()
        Dim d$, a As Date, b As Date, c As Date, da As Date
        d = "2015-01-29 19:23:00.000"
        a = CDate(DateValue(Split(d, " ")(0)))
        b = CDate(DateValue(Left(d, 10)))
        c = CDate(DateValue(Mid(d, 1, 10)))
        da = DateSerial(Split(d, "-")(0), Split(d, "-")(1), Left(Split(d, "-")(2), 2))
        Debug.Print IsDate(a), IsDate(b), IsDate(c), IsDate(da)
        Debug.Print a, b, c, da
    End Sub
    

    输出

    【讨论】:

      猜你喜欢
      • 2014-12-30
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      相关资源
      最近更新 更多