excelvbadrop-down-menudropdownonchange

Excel VBA retrieve and paste values of column A where column B equal specific value


Please see below image example.

Column A and B are static. cell E2 (yellow) is actually a drop down list (or equal to cell which is actually a drop down list).

I need a macro (ideally a sheet change type rather than click button module) that when e2 changes/picked it pastes in cell H2 all the values from column A where column B = e2 (picked value).

enter image description here

in this case, e2 = 7. there are four records in column A where column B=7 (blue highlight) and I want them pasted in H2 (grey column - desired result).

can someone help with a rough guide to do this and the type of functions I should use and I should be able to write it. Thanks


Solution

  • Try this code. It uses the Change event and tests for the cell E2. The code defines the input range automatically. Copy it to the worksheet's code window.

    Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("E2")) Is Nothing Then
      lastrow = Range("A" & Rows.Count).End(xlUp).Row
      Range(Cells(2, 8), Cells(lastrow, 8)).Delete
      pointer = 2
      For i = 2 To lastrow
        If Target = Cells(i, "B") Then
          Cells(pointer, 8) = Cells(i, "A")
          pointer = pointer + 1
        End If
      Next i
    End If
    End Sub