Search code examples
excelvba

VBA If statement not working properly and skipping cell values


I am trying to make a VBA code such that it checks each cell in a range for specific values ("V", "FH", "WM", "N", "LM", "S", "Y", "CP", "IN", "OUT", "END", "G", "H") and if the cell does not contain it, it makes it empty.

The code is the following:

Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    Dim i
    For i = LBound(arr) To UBound(arr)
        If arr(i) = stringToBeFound Then
            IsInArray = True
            Exit Function
        End If
    Next i
    IsInArray = False

End Function

And then I use it like this:

For Each sCell In checkSRange
        If IsInArray(sCell.Value, Array("V", "FH", "WM", "N", "LM", "S", "Y", "CP", "IN", "OUT", "END", "G", "H")) Then
        abcd = 2
        Else: sCell.Value = ""
        End If
    Next sCell

The problem is that this code works for a lot of values but for some reason, cells with the value of "Z" and "M" do not get deleted. I tried adding this to the code:

If sCell.Value = "Z" Or sCell.Value = "M" Then
        sCell.Value = ""
        End If

But even this did not work...

What is the issue????? Thanks.


Solution

  • Ok guys, so sorry but I found the answer. Turns out that I was using the checkSRange. It was not selecting the complete range for the last 20 cells were not getting checked. My code works but also the code of @Vasily also works! I switched to his code over mine.

    But I just wanted to ask, is it possible to make it faster? (Already have disabled screen update) Since it is checking each cell, I think it is a bit too slow...