Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

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 ?

question from:https://stackoverflow.com/questions/65888567/excel-vba-delete-cell-with-time-value-less-then

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...