Last Of: (naive) Function to find the last instance of a string
Stupid-simple function to find the last instance of a string (by sheet) and return a reference to it.
' Find the last (sheet index-wise) instance of a string
' search: The text to search for
' firstSheet: The lower bound of sheet index to search
' lastSheet: The upper bound of sheet index to search
'
' Caveat: Assumes search string is unique on sheet
Function LASTOF(search As String, Optional firstSheet As Integer = 0, Optional lastSheet As Integer = -1) As String
Dim i As Integer
Dim ls As Integer
' If lastSheet wasn't set, use the end of the workbook
If lastSheet > -1 Then ls = lastSheet Else ls = Application.Worksheets.count
' Walk backwards over sheets from ls, stopping at firstSheet
For i = ls To firstSheet - 1 Step -1
Dim ws As Excel.Worksheet
Dim res As Excel.Range
Dim c As Excel.Range
Set ws = Application.Worksheets(i)
' Search for given search text
Set res = ws.Cells.Find(What:=search, _
After:=ws.Cells(1, 1), _
LookIn:=xlValues, _
lookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
MatchByte:=False, _
SearchFormat:=False)
' If found, return address
If Not res Is Nothing Then
LASTOF = res.Address(RowAbsolute:=True, _
ColumnAbsolute:=True, _
ReferenceStyle:=xlR1C1, _
External:=True)
Exit Function
End If
Next i
End Function
This function works nicely with Table At: Who lives here? to get the address for the table.
For example, we can look up the value in a current table row’s NameColumn
in the last table with the same value (starting from worksheet LastSheet
) and return the relevant value from TargetColumn
:
=LET(
lastTable,
TABLEAT(
INDIRECT(
LASTOF(
[@<NameColumn>],
SHEET(<LastSheet>),
SHEET() - 1
),
FALSE
)
),
XLOOKUP(
[@NameColumn],
INDIRECT(CONCAT(lastTable, "[", Table[[#Headers], [<NameColumn>]], "]"))
INDIRECT(CONCAT(lastTable, "[", Table[[#Headers], [<TargetColumn>]], "]")),
NA(),
0,
1
)
)