这将返回对最后三个找到的项目的引用。
然后,您可以使用 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 行:
在此输入代码