0

I am new to VBA for excel and I am stuck with a little problem. I have a list of data and I have two task I want to complete.

The first will delete rows with any values in the J column that is equal to 0;

The second part: I want to loop through the rows left over and delete any rows that the value in I column is greater than the value In J column.

However I'm getting the following error: VBA RunTime Error 91 Object variable or With block variable not set

This is on the line that states:

For rw = .Cells(rows.Count, "E").End(xlUp).Row To 2 Step -1

The full code is

Private Sub clearupdata_Click()

Dim rows As Range, OSQty As Range, value As Long, rw As Long

Set OSQty = Range("j2")

Do Until OSQty.value = ""
    value = Val(OSQty.value)
    If (value = 0) Then
        If rows Is Nothing Then
            Set rows = OSQty.EntireRow
        Else
            Set rows = Union(OSQty.EntireRow, rows)
        End If
    End If
    Set OSQty = OSQty.Offset(1)
Loop

If Not rows Is Nothing Then rows.Delete

With Worksheets(1)   '<~~ worksheet ~~>
    For rw = .Cells(rows.Count, "E").End(xlUp).Row To 2 Step -1
         If .Cells(rw, "I").Value2 > .Cells(rw, "J").Value2 Then
             .rows(rw).EntireRow.Delete
         End If
    Next rw
End With

End Sub
2
  • 1
    Using rows as a variable name for a Range object is not a good idea because there is already a Rows property defined on the Application, Worksheet and Range objects Commented Oct 16, 2015 at 1:33
  • as barrowc said, rows.count might think its the range variable named rows. i tried rename the range it works Commented Oct 17, 2015 at 17:34

2 Answers 2

1

just change:

For rw = .Cells(rows.Count, "E").End(xlUp).Row To 2 Step -1

to

For rw = .Cells(.rows.Count, "E").End(xlUp).Row To 2 Step -1

the difference is when you call the function from a different sheet the rows.count is not for the same sheet so it falls over.

Sign up to request clarification or add additional context in comments.

2 Comments

Solution is ok, but explanation should be slightly different. It has nothing to do with different sheet, rows.count without dot will never work, since .Rows is a method of class Sheet and always must be preceded with an object of this class.
fair enough. I actually thought if sheet in this kind of a case is not specified it takes activesheet by default and I assumed it will run ok, which I just checked it doesn't.
0
Dim rows2 As Range

won't compromise later with .Cells(.rows.Count, "E").End(xlUp).Row,

because rows.count would trigger the error, +1 to barrowc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.