简体   繁体   中英

VBA: How to delete entire row?

enter image description here i am trying to delete a data from a worksheet so i can upload a new data. The problem is when i delete i become a runtime-error '1004'. Here is the function :

Sub deleteOldData(str As String)
    Dim tBookings As ListObject
    Set tBookings = ThisWorkbook.Sheets("Timesheet").ListObjects("tBookings")

    tBookings.AutoFilter.ShowAllData
    tBookings.Range.AutoFilter field:=tBookings.ListColumns("Practice").Index, Criteria1:=str

    If tBookings.DataBodyRange Is Nothing Then
       Exit Sub
    Else 
       tBookings.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
    End If

    tBookings.AutoFilter.ShowAllData
End Sub

How can i avoid this issue?

So it looks like This : when i import a new csv file the old data witch i have existing have to be deleted based on the practice. because the new csv file has a new updated data based on the practice.

Try this. I also added a col variable to avoid repeating code.

Sub deleteOldData(str As String)
    Dim tBookings As ListObject: Set tBookings = ThisWorkbook.Sheets("Timesheet").ListObjects("tBookings")
    Dim col As Integer: col = tBookings.ListColumns("Practice").Index

    tBookings.AutoFilter.ShowAllData
    tBookings.Range.AutoFilter Field:=col, Criteria1:=str

    If tBookings.DataBodyRange Is Nothing Then
       Exit Sub
    Else
       tBookings.ListColumns(col).DataBodyRange.EntireRow.Delete
    End If

    tBookings.AutoFilter.ShowAllData
End Sub

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