As a follow-up to my previous thread, I now need to sort a column of times into chronological order using my VBA code. I've now converted from a simple string of text to a time format, but am having issues sorting into proper order.
For background info, this is a timetable for bus routes. I need to combine the eastbound and westbound times in column H in chronological order. In the column of times (column H), "a" stands for AM, "p" stands for PM, and "x" stands for end-of-day (meaning if a bus route's last time is at 12:30a, it is considered "x"). I have attached my worksheet (which I manually sorted column H chronologically in the desired order for illustration purposes), as well as my current VBA code. Please let me know if I can provide any additional information.
Thanks!
Option Explicit
Sub colon()
Dim lastcolumn As Integer
Dim lastrow As Integer
Dim cell As Range
Dim n As Long
Dim timeWithSpace As String
'Find last column of data
With ActiveWorkbook.ActiveSheet.Range("A1")
lastcolumn = Cells(2, Columns.Count).End(xlToLeft).Column
lastrow = Cells(Rows.Count, lastcolumn).End(xlUp).Row
Range(.Offset(1, lastcolumn - 2), .Offset(lastrow, lastcolumn - 2)).Name = "combined"
End With
'Convert simple time into formatted time
For Each cell In Range("combined")
n = Len(Trim(cell))
Debug.Print timeWithSpace
If n = 4 Or n = 5 Then
cell = Left(Trim(cell), n - 3) & ":" & Right(Trim(cell), 3)
cell.NumberFormat = "h:mm AM/PM"
End If
Next
End Sub
121612 Weekday El Monte Bus Trips.xlsm
Bookmarks