In the code below, I am trying to check 2 date values. If they exist, calculate the days between in column BG. If they don't exist or result is less than 0 then delete the row.
The issue I am having is that once it deletes, a row, it uses Next I, and skips the row directly after it. Ex: row 1 & 2 are missing a date. row 1 gets deleted. row 2 gets pushed up to row 1. then next i, so we are on row 2 now(which was 3) and skips row 2's results. Using i=i-1 seems to crash my program. Also, is there any further way to make my code efficent so that it can iterate through thosands of items faster?
Sub Func4()
Dim N As Long, i As Long, j As Long, cnt As Long, date1 As Date, date2 As Date, date3 As Long ', iold As Long
N = Cells(Rows.Count, "A").End(xlUp).Row
j = 2
cnt = 0
For i = 2 To N 'main
j = j + 1
'iold = i
If Not IsEmpty(Cells(i, "AB").Value) And Not IsEmpty(Cells(i, "AE").Value) Then
date1 = Cells(i, "AB").Value 'AB=Entry Date
date2 = Cells(i, "AE").Value 'AE=Rec'd
date3 = Work_Days(date2, date1)
cnt = cnt + 1
If date3 >= 0 Then
Cells(i, "BG").Value = date3
Else
Rows(i).EntireRow.Delete
'i = i - 1 'HERE
End If
Else
Rows(i).EntireRow.Delete
'i = i - 1 'HERE
End If
'End If
'If i = iold Then
Next i
'Else
'Next
'End If
End Sub
RESOLVED WORKING ANSWER:
Sub Func4()
Dim N As Long, i As Long, j As Long, cnt As Long, date1 As Date, date2 As Date, date3 As Long
N = Cells(Rows.Count, "A").End(xlUp).Row
j = 2
For i = N To 2 Step -1
j = j + 1
If Not IsEmpty(Cells(i, "AB").Value) And Not IsEmpty(Cells(i, "AE").Value) Then
date1 = Cells(i, "AB").Value 'AB=Entry Date
date2 = Cells(i, "AE").Value 'AE=Rec'd
date3 = Work_Days(date2, date1)
cnt = cnt + 1
If date3 >= 0 Then
Cells(i, "BG").Value = date3
Else
Rows(i).EntireRow.Delete
End If
Else
Rows(i).EntireRow.Delete
End If
Next i
End Sub