检查值是否存在于范围内而不进行循环

时间:2016-03-01 03:18:38

标签: excel vba excel-vba

我习惯于python语法在哪里检查7是否在list1中,只需键入7 in list1并返回一个布尔值。我如何在vba中执行类似的操作?

我目前正在大范围内进行循环播放。我想偶尔检查一下我循环的值是否在不同的范围内。如果我不得不在循环中嵌入更多循环,这可能会慢得多。解决这个问题的最快方法是什么?

For i = 400 To 1 Step -1:
'doing other things

'here's some psuedo-code of what I want to do
If Sheets("Sheet2").Cells(i, 2).Value In Sheets("Sheet1").Range("NamedRange")
Sheets("Sheet2").Cells(i, 2).EntireRow.Delete
End If

Next i

2 个答案:

答案 0 :(得分:5)

使用countif,如果它大于零,那么你知道它存在于列表中:

If Application.WorksheetFunction.CountIf(Sheets("Sheet1").Range("NamedRange"), Sheets("Sheet2").Cells(i, 2).Value) > 0 Then
    Sheets("Sheet2").Cells(i, 2).EntireRow.Delete
End If

答案 1 :(得分:1)

这是您仅需一行即可实现的方法

If Not IsError(Application.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
// Value found
End If

示例: 在Sheet5的A列中搜索Blah-Blah

If Not IsError(Application.Match("Blah-Blah", Sheets("Sheet5").Range("A:A"), 0)) Then
   'The value present in that range
End If