Check if value exists in range without looping

和自甴很熟 提交于 2021-02-04 15:54:08

问题


I'm used to python syntax where to check if 7 is in list1 you simply type 7 in list1 and it returns a boolean. How can I perform something like this in vba?

I'm currently looping through a large range. I want to occasionally check if a value i'm looping over is in a different range. This could get much slower if I had to nest more loops into my loops. What's the fastest way to approach this problem?

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

回答1:


Use a countif, if it's greater than zero then you know it exists in the list:

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



回答2:


Here is how you can achieve it in just one line

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

Example: Search for Blah-Blah in column A of Sheet5

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


来源:https://stackoverflow.com/questions/35714043/check-if-value-exists-in-range-without-looping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!