How to convert, or parse, a string to work with dateserial VBA Excel

arrays, excel, vba

Solution

Have you tried using DateValue() instead of DateSerial()?

Using DateValue you can simply use the code

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

And it will resolve to

DateVariable = 10/30/2016

Should be a lot simpler than trying to use DateSerial

You can then add the following line

DateVariable = DateVariable - Day(DateVariable) + 1

To get to the first of the month

Problem

I have a column of data which is composed of two elements (entered as a string). ``` 3/20/2016 6:30:55 PM 3/12/2016 8:15:45 PM 3/8/2016 1:25:18 AM ``` I want to set a variable to be equal to the DateSerial of the date portion of the string noted above. I do not want to pull the data apart and have it reside in separate columns. I wish to leave the formatting intact. I will be loading an array with all the data in the table (multiple columns) but I want the array to be indexed by date. I will run a quicksort on the array and then do some additional cross referencing with the sorted array. However, I cannot get to those stages, with the actual data set, as I'm stuck on the date issue. How can I index by date given the format of the source data? ``` 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 ```

Original source