0

I have built a UDF to return me a comma seperated value of all offsets from matches within a search list. Sort of like a vlookup that returns a list instead of one value.

I run it from a subroutine to test and it works perfectly, when I try and run it from a spreadsheet it errors

This is my testing subroutine:

Sub TestHightlightFindValues()
    Debug.Print FindOffsetMatches(Range("P4").Text, Sheets("Org details").Range("A2:A10119"), 1)
End Sub

And this is my testing function in Excel:

=FindOffsetMatches(P4,'Org details'!$A$2:$A$10119,1)

Here is the Functions code

Function FindOffsetMatches(SearchValue As String, SearchRange As Range, ReturnOffset As Long, Optional MyDelimiter As String = ",")
Dim FirstFound As String, FoundCell As Range, rng As Range, LastCell As Range, ReturnRange As Variant, X As Long, ReturnString As String
On Error GoTo ErrorFound
Set LastCell = SearchRange.Cells(SearchRange.Cells.Count)
Set FoundCell = SearchRange.Find(what:=SearchValue, after:=LastCell)
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
Else
GoTo NothingFound
End If
Set rng = FoundCell
Do Until FoundCell Is Nothing
    Set FoundCell = SearchRange.FindNext(after:=FoundCell)
    Set rng = Union(rng, FoundCell) '<-- This is where it errors, it thinks that FoundCell is empty only when called from an Excel sheet but not when called from a subroutine
    If FoundCell.Address = FirstFound Then Exit Do
Loop
ReturnRange = Split(rng.Address, ",")
ReturnString = Sheets(SearchRange.Worksheet.Name).Range(ReturnRange(LBound(ReturnRange))).Offset(0, ReturnOffset).Text
For X = LBound(ReturnRange) To UBound(ReturnRange)
    If X > LBound(ReturnRange) Then ReturnString = ReturnString & MyDelimiter & Sheets(SearchRange.Worksheet.Name).Range(ReturnRange(X)).Offset(0, ReturnOffset).Text
Next
FindOffsetMatches = ReturnString
Exit Function
'Error Handler
NothingFound:
FindOffsetMatches = "Not found"
Exit Function
ErrorFound:
FindOffsetMatches = "#N/A"
End Function

Any ideas why this is happening?

Thanks in advance.

BigBen
  • 46,229
  • 7
  • 24
  • 40
Dan Donoghue
  • 6,056
  • 2
  • 18
  • 36
  • 1
    https://stackoverflow.com/questions/28715135/udf-using-findnext-seems-to-abort-without-warning. `FindNext` doesn't work in UDFs. – BigBen Nov 19 '19 at 00:01
  • Okay thanks, Based off this info I have now updated the subroutine to fill in the column with the results instead of entering a UDF and it works fine. – Dan Donoghue Nov 19 '19 at 00:05

0 Answers0