Excel VBA代码的条件语句

时间:2017-06-06 16:47:26

标签: excel-vba vba excel

我需要一些帮助。让我们从代码开始:

Range("a1").AutoFilter Field:=1, Criteria1:="W1793-PAS (Agency)"
'exclude 1st row (titles)
With Intersect(Range("a1").CurrentRegion, _
               Range("2:60000")).SpecialCells(xlCellTypeVisible)
    .Rows.Delete
End With
ActiveSheet.ShowAllData
If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilterMode = False

我需要为上面的代码创建一个条件语句,如果没有文本匹配Criteria1(W1793-PAS(Agency)),它将停止该过程。如果没有包含W1793-PAS(代理商)的行,我不希望它运行。

1 个答案:

答案 0 :(得分:1)

只需检查Autofilter是否返回任何内容即可  过滤Range对象中的范围,然后将其删除

Dim rng As Range

'Remove any filters
ActiveSheet.AutoFilterMode = False

With Range("A1")
  .AutoFilter Field:=1, Criteria1:="W1793-PAS (Agency)"
  '~~> Set this here
  Set rng = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
End With

'Remove any filters
ActiveSheet.AutoFilterMode = False

'~~> Check if there were any filtered results and then delete
If Not rng Is Nothing Then rng.Delete