简体   繁体   中英

Delte rows in a range based on a cell value

I have a data on employees in the range Q6:V100. The data is not in table and the data consists of 6 columns(job title, duty, pay etc.) and based on the first column which is "Currently employed" I want to delete the row where the employee is not employed anymore (=""). The first column shows "O" if employed and ""(just a blank) if no . This is the code I have tried. But it shows error message

"Autofilter method of range class failed"

and I have no idea what is wrong... It will grateful if someone can help !

Sub Delete_Rows_Based_On_Value()

Dim ws As Worksheet


  Set ws = ThisWorkbook.Worksheets("Trainings")
  ws.Activate

  'Clear any existing filters
  On Error Resume Next
    ws.ShowAllData
  On Error GoTo 0

  '1. Apply Filter
  ws.Range("Q6:V100").AutoFilter Field:=1, Criteria1:=""

  '2. Delete Rows
  Application.DisplayAlerts = False
    ws.Range("Q7:V100").SpecialCells(xlCellTypeVisible).Delete
  Application.DisplayAlerts = True

  '3. Clear Filter
  On Error Resume Next
    ws.ShowAllData
  On Error GoTo 0

End Sub

I would advise a more robust system, with a notation in Column Q stating: 1 = Employed, 0 = Not employed

Sub Delete_Rows_Based_On_Value()

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Trainings")
    ws.Activate

Dim i As Integer
Dim n as Integer

    n = ws.Range("Q6").CurrentRegion.Rows.Count

    For i = n + 5 To 6 Step -1
        If ws.Cells(i, 17).Value = 0 Then
            ws.Rows(i).Delete
        End If
    Next i

If you do not adapt the new system, change the If-statement to match your current system:

If ws.Cells(i, 17).Value = "" Then

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