The scenario is the following, I have a sheet which has two columns, one I want to match against, the other contains the values I want to copy in case of a match. I have a second sheet which contains the values to search for in the match column and the column to which to copy the value column if we have a match.
This looks like a prime candidate for VLOOKUP but I want to avoid having to hard code the column number as the data sheets contents can vary. So I Find the column based on the header's contents. If there is a way to VLOOKUP the results with this flexibility, then that also works. I can't use a formula, this needs to be in VBA.
Below there are 4 columns defined:
- toFindCol: this contains the master list of values I am going to try and find in the toMatch column
- toMatchAgainstCol: this contains the list of values i want to match the toFindCol values against
- valueCol: this contains the value I want to copy, in case there is a match, the value has to come from the row on which the match occurred
- resultsCol: this is where i want to copy the value to, the value needs to be copied to the row of the toFind value
For some reason the code below gives a "Type Mismatch" error.
Eventually I want to wrap this into a function/subroutine so I can pass in the sheets and column headers and get it to work it's magic. Brownie points for who can do that :)
Dim toFindCol As Range
Dim toMatchAgainstCol As Range
Dim valueCol As Range
Dim resultsCol As Range
Dim match As Variant
Set toFindCol = cohortDataSetSht.Columns(1).EntireColumn
Set toMatchAgainstCol = userSht.Cells.Find("id", , xlValues, xlWhole).EntireColumn
Set valueCol = userSht.Cells.Find("cdate", , xlValues, xlWhole).EntireColumn
Set resultsCol = cohortDataSetSht.Columns(4)
For Each findMe In toFindCol
Set match = toMatchAgainstCol.Find(What:=findMe, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows)
If Not match Is Nothing Then
resultsCol.Cells(findMe.Row, 0).Value = valueCol.Cells(match.Row, 0).Value
End If
Next findMe