首页 > 解决方案 > 处理数组中的时间戳时丢失毫秒

问题描述

我正在使用从文本文件导入的数据在 Excel 中使用 VBA 处理数字。时间戳数据的格式为“dd-mmm-yyyy hh:mm:ss.000”,整列的数字格式设置为“dd-mmm-yyyy hh:mm:ss.000”。导入后,导入的列与文本文件完全匹配(例如,16-Mar-2020 16:10:15.175)。

作为数字运算的一部分,我将导入的列读入一个称为时间戳的变体数组:

Dim timestamp As Variant
timestamp = Range(.Cells(1, Timestamp_Column), .Cells(NumRows, Timestamp_Column))

当我使用断点检查数据时,它被格式化为日期,但没有可见的时间戳。它的格式为:#16-Mar-20 4:10:15 PM#

然后我将其粘贴到与原始数据具有相同数字格式的目标表中:

Private Function FillColumnData(theArray As Variant, transpose As Boolean, _
  sheetname As String, destCol As Integer) As Variant

Dim destColRange As Range
Dim tempArray as Variant
Dim maxrow As Long

maxrow = NumRows()

' Transpose the array?
If (transpose) Then
    tempArray = TransposeArray(theArray) ' Transpose the array
Else
    tempArray = theArray ' The timestamp array is not transposed
End If

With Sheets(sheetname)
    Set destColRange = .Columns(destCol)
    Set destColRange = destColRange.resize(maxrow, 1)
    destColRange.value = tempArray
End With

结果列是完整的并且与原始列数据匹配,除了所有毫秒值都是 0:例如 original = "16-Mar-2020 16:10:15.175"; 复制 =“2020 年 3 月 16 日 16:10:15.000”。

将数组粘贴回目标表时,我可以强制执行一些操作吗?

提前感谢您的帮助!

标签: arraysexcelvbadatetimemilliseconds

解决方案


向/从 VBA/工作表传递日期有时很棘手。1Excel 将日期存储为带有=的序列号1-Jan-1900。VBA 作为显式日期数据类型。

最简单的方法是将您的赋值语句替换为:

timestamp = Range(.Cells(1, Timestamp_Column), .Cells(NumRows, Timestamp_Column)).Value2

这样,您将传递 Double 而不是 Date 数据类型。

另一种方法是遍历您的时间戳数组,将每个元素替换为,但直接使用该属性CDbl(timestamp(x,y))访问该值似乎更有效。Value2

这将提供未格式化的值并包括毫秒

概念代码证明

Option Explicit

Sub dtStuff()
    Dim R As Range: Set R = Range("A1:a2")
    Dim v, w
    v = R
    w = R.Value2

    With R.Offset(0, 1)
        .NumberFormat = R.NumberFormat
        .Value = v
    End With

    With R.Offset(0, 2)
        .NumberFormat = R.NumberFormat
        .Value = w
    End With

End Sub

在此处输入图像描述


推荐阅读