I have written some VBA that is supposed to look at the value of cells in the range L28:L41 and if the cell says "Submitted" or "Cancelled", clear the contents of that cell and the three next to it Col I-L). It is supposed to do this on each employee’s worksheet (to the same cells).
I have a script that seems to be working, but a few times when I have tested it I have gotten an "Out of Range" error on the "DeleteRow.Select" row of code. Sometimes I get this error, but usually I do not. I have been trying to figure out what specific situations are causing this error, but I can’t seem to find a pattern. I’m pretty confident in what I put together because it works most of the time. But, I am going to be sharing this worksheet with other people, so I want to make sure they never get this error. Can you help me understand what is wrong with my code and how to prevent this?
Sub DeleteIssuedRows()
Application.ScreenUpdating = False
Dim Employee As Worksheet
For Each Employee In Sheets(Array("Sandra", "Diana", "Caitlin", "Kimberly", "Teresa"))
Set DeleteRng = Employee.Range("L28:L41")
Dim DeleteCell As Range
Dim DeleteRow As Range
For Each Cell In DeleteRng
If Cell.Value = "Issued" Or Cell.Value = "Cancelled" Then
Set DeleteCell = Cell
Set DeleteRow = Range(DeleteCell.Offset(0, -3), DeleteCell)
DeleteRow.Select
DeleteRow.ClearContents
Else
End If
Next Cell
Next Employee
Application.ScreenUpdating = True
End Sub
>Solution :
When you apply the full name of a range it will give you the range you want, like here
Set DeleteRng = Employee.Range("L28:L41")
but if you use only Range or Cells objects this can refer to another sheet.
Apply the sheet name for them and you get the required range, like this
Set DeleteRow = Employee.Range(DeleteCell.Offset(0, -3), DeleteCell)