VB Vlookup会找到最后一场比赛

时间:2017-02-03 04:38:56

标签: excel-vba vlookup vba excel

  • 如何创建一个VB Vlookup,它将找到最后一个匹配或最后一个匹配?
  • 从我的范围B4:B9999
  • 的底部查找

我试过了:

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或不工作。

1 个答案:

答案 0 :(得分:0)

这将返回对最后三个找到的项目的引用 然后,您可以使用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

修改
要在用户表单上实践代码:

  • 创建一个名为ComboBox3的组合框。
  • 创建名为Label1的标签。确保标签宽而高,足以显示所有数据(三行)。

将此代码添加到用户表单中 (您必须在模块中拥有Find_Last_Three。如果需要,您可以删除Test

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

注意:rCell.Offset(,1)rcell.Offset(,2)是获取额外信息的地方 - 从B列偏移1和2列。

使用我的示例数据,它返回此结果,显示 H 的最后三次出现在第11,15和18行:
enter image description here     在这里输入代码