I’ve written this code to delete duplicate rows in a column of an Excel spreadsheet. I’m not sure how to, or if it is possible to, exit the while loop from within the function itself. I don’t want to add a second condition to the loop (such as Counter < 100) because I don’t want it to run more than needed.
Sub Deletion()
Dim Cond As Boolean
Dim Counter As Integer
Cond = True
Counter = 2
While Cond = True
RecDel (Counter)
Counter = Counter + 1
Wend
End Sub
Function RecDel(Varii As Integer)
Set CurrentCell = Workbooks("Duplicate.xls").Sheets("Sheet1").Cells(Varii, 2)
If CurrentCell.Value = CurrentCell.Offset(1, 0).Value And CurrentCell.Offset(1, 0).Value <> "" Then
Workbooks("Duplicate.xls").Sheets("Sheet1").Rows(Varii + 1).Delete
RecDel (Varii) 'Repeats deletion until this row and the next row are different
ElseIf CurrentCell.Offset(1, 0).Value = "" Then
Cond = False 'This can't change the global variable and break the loop
Else
End If
End Function
The problem is that your
Condin the function and theCondin the sub are not the same. They are both local variables. You could makeCondglobal to share it between the 2. Alternatively, you could have your function return a Boolean and get rid of theCondflag altogether:And in your calling sub, check the status of RecDel: