Home » excel » excel – VBA to check if values from one sheet are found in another sheet

excel – VBA to check if values from one sheet are found in another sheet

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to develop a macro to check if values from one column in a sheet are found as substrings in the columns of another sheet.

So, I want to check each cell of my first column, and if it’s not empty, compare it to every cell in the second sheet, of columns 1 and 3.

For this I used a “for each” loop, and then a “for” loop, with i from 1 to Rows.Count.

This is where it gets tricky as I’m not sure if it’s the right way to approach this. Also, the parameters of the instr() function to check if values are found as substrings don’t seem to match, as I get a “type mismatch” error when trying to run the code.

Sub test()

Set Wks1 = Worksheets("Sheet1")
Set Wks2 = Worksheets("Sheet2")

Dim i As Long
Dim rng As Range, cell As Range

Set rng = Wks1.Range("C3:O69")

For Each cell In rng

    If Not (IsEmpty(cell.Value)) Then

        For i = 1 To Wks2.Rows.Count

            If (InStr(Cells(i, 1), cell.Value, 1) <> 0) Or (InStr(Cells(i, 3), _
                                                            cell.Value, 1) <> 0) Then
                Cells(i, 4) = "String contains substring"

            End If

        Next i

    End If

Next cell

End Sub
How to&Answers:

That should work

Sub test()

Dim i As Long
Dim rng As Range, cell As Range
Dim lastRow as Long

Set Wks1 = Worksheets("Sheet1")
Set Wks2 = Worksheets("Sheet2")

Set rng = Wks1.Range("C3:O69")
lastRow = Wks2.Cells(Rows.Count, 1).End(xlUp).row
For Each cell In rng

    If Not (IsEmpty(cell.Value)) Then

        For i = 1 To lastRow

            With Wks2

                If (InStr(.Cells(i, 1), cell.Value) <> 0) Or (InStr(.Cells(i, 3), cell.Value) <> 0) Then

                   .Cells(i, 4) = "String contains substring"

                End If

            End With
        Next i

    End If

Next cell

End Sub