根据单元格值删除行

时间:2019-02-13 01:42:26

标签: excel vba

我想删除数据表中带有“ 3DO”或“ DOS”列B单元格值的任何行,并向上移动其余单元格。

数据表的屏幕截图
enter image description here

工作簿名称:StackOverflowTest.xlsm

工作表名称:Sheet1

单元格范围:A1:J100000

列的值:B

要搜索的值:“ 3DO”,“ DOS”

我的理解是,可以更改以下VBA代码以实现此目的:

Sub Delete_Rows_Based_On_Value()
'Apply a filter to a Range and delete visible rows
'Source: https://www.excelcampus.com/vba/delete-rows-cell-values/


Dim ws As Worksheet

  'Set reference to the sheet in the workbook.
  Set ws = ThisWorkbook.Worksheets("Regular Range")
  ws.Activate 'not required but allows user to view sheet if warning message appears

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

  '1. Apply Filter
  ws.Range("B3:G1000").AutoFilter Field:=4, Criteria1:=""

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

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

End Sub

更新:

@ Harun24HR的这段代码对我来说似乎很有用

Sub DelVisible()
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("RAW")

    ws.Range("$A$1:$J$100000").AutoFilter Field:=2, Criteria1:="=3DO", _
        Operator:=xlOr, Criteria2:="=DOS"

    ws.Range("$A$2:$J$100000").SpecialCells(xlCellTypeVisible).EntireRow.Delete
    ws.Range("$A$1:$J$100000").AutoFilter

End Sub

但是现在我想在此语句中添加更多要搜索的条件,但我不清楚如何执行此操作。假设我要查找“ 3DO”,“ DOS”和“ Mac”,那么除了此语句外,我还将如何添加“ Mac”标准?

更新#2

感谢@ user11053804,我有一个可以解决3个以上标准的有效解决方案

Sub RemoveOldPlatforms()
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("RAW")

    ws.Range("$A$1:$J$100000").AutoFilter Field:=2, Criteria1:=Array("3DO", "All Other", "DOS", "Mac"), Operator:=xlFilterValues

    ws.Range("$A$2:$J$100000").SpecialCells(xlCellTypeVisible).EntireRow.Delete
    ws.Range("$A$1:$J$100000").AutoFilter

End Sub

2 个答案:

答案 0 :(得分:1)

接下来的代码呢?您能尝试一下并反馈给我们吗?

Sub DelVisible()
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("Regular Range")

    ws.Range("$A$1:$J$10000").AutoFilter Field:=2, Criteria1:="=3DO", _
        Operator:=xlOr, Criteria2:="=DOS"

    ws.Range("$A$2:$J$10000").SpecialCells(xlCellTypeVisible).EntireRow.Delete
    ws.Range("$A$1:$J$10000").AutoFilter

End Sub

答案 1 :(得分:0)

您的AutoFilter语句不足。

ws.Range("B3:B1000").AutoFilter Field:=1, Criteria1:="EDO", Criteria2:="DOS", operator:=xlOr

其他条件要求使用带有xlFilterValues的数组。

ws.Range("B3:B1000").AutoFilter Field:=1, Criteria1:=array("EDO", "DOS", "All Others"), operator:=xlFilterValues