Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value exists in range without looping

Tags:

excel

vba

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
like image 701
click here Avatar asked Mar 13 '23 02:03

click here


2 Answers

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
like image 83
Dan Donoghue Avatar answered Mar 31 '23 10:03

Dan Donoghue


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
like image 20
Hari Das Avatar answered Mar 31 '23 11:03

Hari Das