如何转换或parsing一个string以使用dateserial VBA Excel

我有一个由两个元素组成的数据列(作为stringinput)。

3/20/2016 6:30:55 PM 3/12/2016 8:15:45 PM 3/8/2016 1:25:18 AM 

我想设置一个variables等于上面提到的string的date部分的DateSerial。

我不想将数据分开,并将其分散在不同的列中。 我希望保持格式不变。

我将加载一个数组与表中的所有数据(多列),但我想按date索引数组。 我将在数组上运行一个快速sorting,然后对sorting数组做一些额外的交叉引用。 但是,我不能进入这些阶段,实际的数据集,因为我被困在date问题。

如何根据源数据的格式按date进行索引?

 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 

你有没有尝试使用DateValue()而不是DateSerial()?

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

 DateVariable = DateValue("10/30/2016 09:18 pm") 

这将解决

 DateVariable = 10/30/2016 

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

然后你可以添加下面一行

 DateVariable = DateVariable - Day(DateVariable) + 1 

要到本月的第一个月

更换:

 d = DateSerial(Year(.Cells(RowCount, 1)), Month(.Cells(RowCount, 1)), 1) 

有:

 Dim s As String s = .Cells(RowCount, 1) ary = Split(s, " ") bry = Split(ary(0), "/") mm = CLng(bry(0)) yy = CLng(bry(2)) d = DateSerial(yy, mm, 1)