1

Background:

I have an excel file with two sheets namely 'sheet1' and 'sheet2'. Both the sheets have same headers.

Sheet1- header starts from columnB and Sheet2- from columnA.

The first Header(in both sheets) is unique ID.

Both the columns in respective sheets has an array of values

Problem:

How do I search if the values in sheet2(columnA) are present in sheet1 (columnB) using VBA..?

My theoritical procedure:

Loop until UID in 'Sheet1' is empty

  1. Go to 'sheet2'
  2. Read UID value
  3. Go to 'sheet1'
  4. Search in UID column for read UID
  5. If found

5.1 some operations

  1. If not found

6.1 some operations

Loop end

Please guide me on how can I do this search activity.

Thanks in advance!

2 Answers 2

0

You can use a dictionary to do this. Using a dictionary means you read the values in sheet1 once rather than for each value in sheet2.

Sub CompareColumns()

    Dim dict As Object
    Set dict = CreateObject("Scripting.dictionary")

    Dim sheet1 As Worksheet, Sheet2 As Worksheet
    Set sheet1 = ThisWorkbook.Worksheets("Sheet1")
    Set Sheet2 = ThisWorkbook.Worksheets("Sheet2")

    ' Read values from sheet1 to dictionary
    Dim lastRow As Long
    lastRow = sheet1.Cells(sheet1.Rows.Count, 1).End(xlUp).Row
    Dim i As Long
    For i = 1 To lastRow
        ' Store value to dictionary
        dict(sheet1.Cells(i, 1).Value) = 1
    Next

    ' Read from sheet2 and check if each value exists
    lastRow = Sheet2.Cells(Sheet2.Rows.Count, 2).End(xlUp).Row
    For i = 1 To lastRow
        ' Check if value exists in dictionary
        If dict.exists(Sheet2.Cells(i, 2).Value) Then
            ' found
        Else
            ' not found
        End If
    Next

End Sub
0

You can start with something like this:

Sub Test()
    Dim AlastRow As Integer
    Dim Blastrow As Integer

    With ThisWorkbook.Worksheets("Sheet1")
        Blastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
    End With

    With ThisWorkbook.Worksheets("Sheet2")
        AlastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    Dim ra As Range
    Dim rb As Range

    With ThisWorkbook
        Set ra = .Worksheets("Sheet1").Range("A1", "A" & AlastRow)
        Set rb = .Worksheets("Sheet2").Range("B1", "A" & AlastRow)
    End With

    For Each cellb In rb.Cells
        For Each cella In ra.Cells
            If cella.Value = cellb.Value Then
                'Found match, do stuff
            Else
                'Did not found match do stuff too
            End If
        Next
    Next
End Sub

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.