[英]VLookup Macro in Excel
I have an excel workbook with two worksheets. 我有一个带有两个工作表的excel工作簿。 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.
工作表A中包含多个名称,每个名称位于不同的列中,而工作表B包含工作表A中的相同名称和包含日期的第二列。 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. 我要做的是设置一个调用VLookup的宏,并将工作表A中名称列中的名称作为工作表B上的搜索参数传递。一旦在工作表B上找到该名称,它就会返回日期。 Currently I am manually having this data pulled by hard coding the following vlookup in a column on Worksheet A.
目前,我通过在工作表A的列中对以下vlookup进行硬编码来手动获取此数据。
=VLOOKUP(A2,'Worksheet B'!A:B,2,FALSE)
Any suggestions and help is greatly appreciated. 非常感谢任何建议和帮助。
Thank you. 谢谢。
You can use worksheet functions within VBA. 您可以在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. 您必须编辑工作表名称并调整与示例数据中提供的列不同的任何列。
This isn't vlookup, but it will get the results you want. 这不是vlookup,但它会得到你想要的结果。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.