简体   繁体   中英

Excel VBA - delete cell with time value less then

I'm trying to delete specific range based on a time value in the column "J". So far I got this:

Dim wb As Workbook
Dim c As Range
Dim zakres As Range
Dim zakres2 As Range
Dim all As String
Dim all2 As Range
Dim ile As String
Dim czas As Range

Set wb = ThisWorkbook
Set czas = wb.Worksheets("Dane").Range("J2")

ile = Application.WorksheetFunction.CountA(wb.Worksheets("Dane").Range("L:L"))

For i = 1 To ile
    If czas.Value < "00:01:00" Then
        Set zakres = czas.Offset(0, 0)
        Set zakres2 = czas.Offset(0, 2)
        all = zakres.Address & ":" & zakres2.Address
        Set all2 = Range(all)
        all2.Delete Shift:=xlUp
    Else
        Set czas = czas.Offset(1, 0)
    End If
Next i

In the line If czas.Value < "00:01:00" Then I'm getting the 424 run time error - Object required. It confuses me, since the variable czas is already declared...

Any ideas why it's happening and how to deal with it?

When you delete the row that contains the range czas you also delete that range object. A null range has no property .value which is why you are getting an object required error.

A good way to mass delete range object is to use union to create non-contiguous ranges and then delete them all at once. This spares you the weirdness of shifting rows in a loop and also will significantly improve speed as deleting is pretty expensive.

Dim wb As Workbook
Dim c As Range
Dim zakres As Range
Dim zakres2 As Range
Dim ile As String
Dim czas As Range
Dim i As Long
Dim delrng As Range

Set wb = ThisWorkbook
Set czas = wb.Worksheets("Dane").Range("J2")

ile = Application.WorksheetFunction.CountA(wb.Worksheets("Dane").Range("L:L"))

For i = 1 To ile
    If czas.Value < "00:01:00" Then
        Set zakres = czas.Offset(0, 0)
        Set zakres2 = czas.Offset(0, 2)
        If delrng Is Nothing Then
            Set delrng = Range(zakres, zakres2)
        Else
            Set delrng = Union(delrng, Range(zakres, zakres2))
        End If
    End If
    Set czas = czas.Offset(1, 0)
Next i
If Not delrng Is Nothing Then
    delrng.Delete
end if

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM