运行时错误91对象变量或未设置块变量

时间:2015-10-15 14:00:37

标签: excel vba excel-vba

我是VBA for excel的新手,我遇到了一个小问题。我有一个数据列表,我有两个任务要完成。

第一个将删除J列中任何等于0的值的行;

第二部分:我想遍历剩下的行并删除I列中的值大于J列中的值的所有行。

但是我收到以下错误:VBA运行时错误91对象变量或未设置块变量

这是在说明:

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

完整的代码是

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 个答案:

答案 0 :(得分:1)

只是改变:

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

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

不同之处在于,当您从另一个工作表调用该函数时,rows.count不适用于同一工作表,因此会失败。

答案 1 :(得分:0)

Dim rows2 As Range

稍后不会与.Cells(.rows.Count, "E").End(xlUp).Row

妥协

因为rows.count会触发错误,+1会发生barrowc