Excel VB Vlookup将查找最后一个匹配项 如何创建一个VB Vlookup来查找最后一个匹配项或最后3个匹配项 从我的范围底部查找B4:B9999
我试过:Excel VB Vlookup将查找最后一个匹配项 如何创建一个VB Vlookup来查找最后一个匹配项或最后3个匹配项 从我的范围底部查找B4:B9999,excel,vlookup,vba,Excel,Vlookup,Vba,我试过: Private Sub FindRecord_Click() Label21 = Application.WorksheetFunction.VLookup(ComboBox3.Value, Worksheets("Transactions").Range("B4:P9999"), 1, False) Label21 = Application.WorksheetFunction.VLookup(ComboBox3.Value, Worksheets("Transactions").
Private Sub FindRecord_Click()
Label21 = Application.WorksheetFunction.VLookup(ComboBox3.Value, Worksheets("Transactions").Range("B4:P9999"), 1, False)
Label21 = Application.WorksheetFunction.VLookup(ComboBox3.Value, Worksheets("Transactions").Range("B4:P9999"), 2, False)***
End Sub
Private Sub UserForm_Initialize()
ComboBox3.RowSource = "'[TEST46.xlsm]Transactions'!B4:B9999"**
End Sub
我试过谷歌,那些提供的解决方案是为excel vlookup或不工作 这将返回对最后三个找到的项目的引用。
然后,您可以使用
OFFSET
从相邻单元格返回值。代码有点凌乱,可能可以改进,但它给了您想法
Public Sub Test()
Dim MyRange As Range
Dim rCell As Range
'Look for the value 4 in second column of Sheet3.
Set MyRange = Find_Last_Three(4, Sheet3.Columns(2))
If Not MyRange Is Nothing Then
For Each rCell In MyRange
'Print the values from the 2 cells to the right of the found cells.
Debug.Print rCell.Offset(, 1) & " : " & rCell.Offset(, 2)
Next rCell
End If
End Sub
Public Function Find_Last_Three(ValueToFind As Variant, RangeToLookAt As Range) As Range
Dim rFound As Range
Dim rReturnedRange As Range
Dim sFirstAddress As String
Dim x As Long
With RangeToLookAt
Set rFound = .Find(What:=ValueToFind, _
After:=.Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchDirection:=xlPrevious)
If Not rFound Is Nothing Then
Set rReturnedRange = rFound
sFirstAddress = rFound.Address
For x = 1 To 2
Set rFound = .FindPrevious(rFound)
If rFound.Address <> sFirstAddress Then
Set rReturnedRange = Union(rReturnedRange, rFound)
End If
Next x
End If
End With
Set Find_Last_Three = rReturnedRange
End Function
注意:rCell.Offset(,1)
和rCell.Offset(,2)
是从中获取额外信息的位置-从B列偏移1和2列
对于我的示例数据,它返回的结果显示H的最后三次出现在第11、15和18行:在这里输入代码你可以创建你自己的
MyVlookUp
作为自定义项,在里面你只需使用一个常规的For
循环,从结尾开始。并找到每行的匹配项。谢谢Shai,我将首先查看Darren Bartrup Cook提供的模板。嗨,Darren,希望你能指导我?我在“将2个单元格中的值打印到找到的单元格的右侧”上找不到任何结果。在通过使用变量模拟表3运行上述命令后,我更新了我的答案,以显示如何在表单中使用代码。您的原始代码似乎有一个标签和组合框,所以我们使用了它们。1000谢谢Darren,我将对其进行测试并发表评论。这是非常有价值的分享,因为我在互联网上找不到任何其他相同的分享。
Private Sub UserForm_Initialize()
Me.ComboBox3.RowSource = "Transactions!B4:B9999"
End Sub
Private Sub ComboBox3_Change()
Dim rLastThree As Range
Dim rCell As Range
Set rLastThree = Find_Last_Three(Me.ComboBox3.Value, Range(Me.ComboBox3.RowSource))
If Not rLastThree Is Nothing Then
Me.Label1.Caption = ""
For Each rCell In rLastThree
Me.Label1.Caption = Me.Label1.Caption & rCell.Offset(, 1) & " : " & rCell.Offset(, 2) & vbCr
Next rCell
End If
End Sub