Set Function Equal to "ERROR" on Error

BetterBeef

New Member
Joined
Mar 18, 2010
Messages
42
I have the following custom function that finds the "nth" time a particular string shows up in a range:

Code:
Public Function Nth_Occurrence(range_look As Range, find_it As String, _
    occurrence As Long, offset_row As Long, offset_col As Long)
Dim lCount As Long
Dim rFound As Range
    On Error GoTo Err_ERROR
 
    Set rFound = range_look.Cells(1, 1)
        For lCount = 1 To occurrence
            Set rFound = range_look.Find(find_it, rFound, xlValues, xlWhole)
        Next lCount
    Nth_Occurrence = rFound.Offset(offset_row, offset_col)
 
End Function

I want to know how I can return the string "ERROR" to the function Nth_Occurrence.

Essentially when there is an error in the function, I want to run the code below:

Nth_Occurrence = "ERROR"

Is this possible?
 

Excel Facts

How can you automate Excel?
Press Alt+F11 from Windows Excel to open the Visual Basic for Applications (VBA) editor.
Untested but perhaps

Code:
Public Function Nth_Occurrence(range_look As Range, find_it As String, _
    occurrence As Long, offset_row As Long, offset_col As Long) As Variant
Dim lCount As Long
Dim rFound As Range
On Error GoTo Err_ERROR

Set rFound = range_look.Cells(1, 1)
For lCount = 1 To occurrence
    Set rFound = range_look.Find(find_it, rFound, xlValues, xlWhole)
Next lCount
Nth_Occurrence = rFound.Offset(offset_row, offset_col)
Exit Function
Err_ERROR:
Nth_Occurrence = [#N/A]
End Function
 
Upvote 0

Forum statistics

Threads
1,215,522
Messages
6,125,312
Members
449,218
Latest member
Excel Master

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top