Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 88835

Returning an offset from multiple occurrences of a given input in a range

$
0
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.


Viewing all articles
Browse latest Browse all 88835

Trending Articles