Reputation: 33
I have an excel workbook with two worksheets. Worksheet A has the several names in it with each name in a different column and Worksheet B contains the same names that are in worksheet A and a second column containing dates. Example:
Worksheet A. Worksheet B.
Name. Name. Dates
Sean Jake 11/13/15
Jake Sean 10/11/14
Tom. Chris 12/12/15
What I am trying to do is set a macro that calls VLookup and passes the name from the name column in Worksheet A as a search parameter on Worksheet B. once the name is found on Worksheet B, it returns the date. Currently I am manually having this data pulled by hard coding the following vlookup in a column on Worksheet A.
=VLOOKUP(A2,'Worksheet B'!A:B,2,FALSE)
Any suggestions and help is greatly appreciated.
Thank you.
Upvotes: 3
Views: 831
Reputation:
You can use worksheet functions within VBA. This macro takes advantage of them by returning the values they discover into the appropriate cells.
Sub auto_VLOOKUP()
Dim rw As Long, wsB As Worksheet
Set wsB = Worksheets("Worksheet B")
With Worksheets("Worksheet A")
For rw = 2 To .Cells(Rows.Count, 1).End(xlUp).Row
If CBool(Application.CountIf(wsB.Columns(1), .Cells(rw, 1).Value)) Then
' VLOOKUP is typically used to return data from the right of the lookup column
.Cells(rw, 2) = Application.VLookup(.Cells(rw, 1).Value, wsB.Columns("A:B"), 2, False)
' INDEX/MATCH function pairs are used to wider scope
.Cells(rw, 3) = Application.Index(wsB.Columns("N"), Application.Match(.Cells(rw, 1).Value, wsB.Columns("A"), 0))
End If
Next rw
.Cells(2, 2).Resize(rw - 2, 1).NumberFormat = "m/d/yyyy"
End With
Set wsB = Nothing
End Sub
You will have to edit the worksheet names and adjust any columns that are not the same as the ones you provided in your sample data.
Upvotes: 1
Reputation: 6982
This isn't vlookup, but it will get the results you want.
Sub Button1_Click()
Dim ws As Worksheet, sh As Worksheet
Dim Rws As Long, Rng As Range
Dim c As Range, FndC As Range, shRng As Range
Set ws = Sheets("Sheet1")
Set sh = Sheets("Sheet2")
Set shRng = sh.Range("A:A").SpecialCells(xlCellTypeConstants, 23)
With ws
Rws = .Cells(Rows.Count, "A").End(xlUp).Row
Set Rng = .Range(.Cells(1, 1), .Cells(Rws, 1))
End With
For Each c In Rng.Cells
Set FndC = shRng.Find(what:=c, lookat:=xlWhole)
If Not FndC Is Nothing Then
c.Offset(0, 1) = FndC.Offset(0, 1)
Else: c.Offset(0, 1) = "Not Found"
Exit Sub
End If
Next c
End Sub
Upvotes: 0