如何转换或解析字符串以使用日期序列 VBA Excel

War*_*dos 3 arrays excel vba

我有一列数据,它由两个元素组成(作为字符串输入)。

3/20/2016 6:30:55 PM
3/12/2016 8:15:45 PM
3/8/2016 1:25:18 AM
Run Code Online (Sandbox Code Playgroud)

我想将一个变量设置为等于上面提到的字符串日期部分的 DateSerial。

我不想将数据分开并将其驻留在单独的列中。我希望保持格式不变。

我将加载一个包含表中所有数据(多列)的数组,但我希望该数组按日期进行索引。我将对数组运行快速排序,然后对排序后的数组进行一些额外的交叉引用。但是,我无法使用实际数据集进入这些阶段,因为我被困在日期问题上。

给定源数据的格式,如何按日期索引?

Dim d as Date
Dim arTemp
Dim arTemp1
Dim WS As Worksheet
Dim list As Object, list1 As Object
Dim RowCount as Integer, y As Integer

Set list = CreateObject("System.Collections.SortedList")
Set list1 = CreateObject("System.Collections.SortedList")

For Each WS In WorkSheets
    With WS
        For RowCount = 7 to 207
            'Works perfectly if the data in Column 1 is actually a date
            d = DateSerial(Year(.Cells(RowCount, 1)), Month(.Cells(RowCount, 1)), 1)

                If list.Containskey(d) Then
                    arTemp = list(d) 
                    arTemp1 = list1(d)'omitted from code below but follows the same format
                Else
                    ReDim arTemp(8)
                    ReDim arTemp1(8)
                End If
                For y = 2 to 7 'Cycle through the columns and load array/list
                    arTemp(0) = arTemp(0) + .Cells(RowCount, y) 'Grab Km
                    arTemp(1) = arTemp(1) + .Cells(RowCount, y) 'Grab Route Hrs
                    arTemp(2) = arTemp(2) + .Cells(RowCount, y) 'Grab No. Deliveries
                    arTemp(3) = arTemp(3) + .Cells(RowCount, y) 'Grab No. of Del Pieces
                    arTemp(4) = arTemp(4) + .Cells(RowCount, y) 'Grab No. Pick-ups
                    arTemp(5) = arTemp(5) + .Cells(RowCount, y) 'Grab No. of PU Pieces
                    arTemp(6) = arTemp(6) + .Cells(RowCount, y) 'Grab Total Stops
                    arTemp(7) = arTemp(7) + .Cells(RowCount, y) 'Grab Total Pieces
                    arTemp(8) = arTemp(8) + 1
                    list(d) = arTemp
            'do other stuff here .........................................
            Next y
        Next RowCount
    End With
Next
Run Code Online (Sandbox Code Playgroud)

dan*_*anl 5

您是否尝试过使用 DateValue() 而不是 DateSerial()?

使用 DateValue 您可以简单地使用代码

DateVariable = DateValue("10/30/2016 09:18 pm")
Run Code Online (Sandbox Code Playgroud)

它会解决

DateVariable = 10/30/2016
Run Code Online (Sandbox Code Playgroud)

应该比尝试使用 DateSerial 简单得多

然后,您可以添加以下行

DateVariable = DateVariable - Day(DateVariable) + 1
Run Code Online (Sandbox Code Playgroud)

到本月的第一天