I have this Macro below that is meant to delete rows based on the time. I run the macro and im getting a "subscript out of range" error. I used this macro before on another worksheet and it worked fine. Im updating the macro for this new worksheet but cant get it to work. I have a worksheet named "Item_Transaction"
Rich (BB code):
Dim wsItem_Transaction As Worksheet
Dim lastRow As Long
Dim currentTime As Date
Dim cutoffTime As Date
Dim i As Long
' Set wsItem_Transaction to the correct worksheet
Set wsItem_Transaction = ThisWorkbook.Worksheets("Item_Transaction") ' Replace "Item_Transaction" with your actual sheet name
Application.ScreenUpdating = False
With wsItem_Transaction.Sort
.SortFields.Clear
.SortFields.Add2 Key:=wsItem_Transaction.Range("A1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange wsItem_Transaction.Range("$A$1").CurrentRegion
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
wsItem_Transaction.Columns("E:E").NumberFormat = "[$-en-US]m/d/yy h:mm AM/PM;@"
' Find the last row with data in column E
lastRow = wsItem_Transaction.Cells(wsItem_Transaction.Rows.Count, "E").End(xlUp).Row
' Get the current date and time
currentTime = Now
' Set the cutoff time for the current day at 6:50 AM
cutoffTime = DateValue(currentTime) + TimeValue("06:50:00")
' Loop from the last row to the first row (bottom-up)
For i = lastRow To 1 Step -1
' Check if the timestamp in column B is before the cutoff time
If IsDate(wsItem_Transaction.Cells(i, 2).Value) Then
If wsItem_Transaction.Cells(i, 2).Value < cutoffTime Then
' Delete the row if the condition is met
wsItem_Transaction.Rows(i).Delete
End If
End If
Next i
Application.ScreenUpdating = True
MsgBox "Macro complete!"
End Sub