Sub Test__FirstOccurrence()
MsgBox FirstOccurrence(ThisWorkbook, ActiveSheet.name, "A7:A101111", "", True, False)
End Sub
Function FirstOccurrence( _
book As Workbook, _
sheetName As String, _
searchRange As String, _
search As String, _
CaseSensitive As Boolean, _
match_Entire_Cell_Contents As Boolean _
)
'Where I originally first heard about Range.Find: https://www.thespreadsheetguru.com/the-code-vault/2014/4/21/find-all-instances-with-vba (In the "Sub HighlightFindValues()".)
'NOTE: CStr(lastDataRow + 1) when searching for the first cell that is blank ("") or contains contents ("*") . . . definitely do this
'when searching through rows of a column in an Excel TABLE!!!! I don't know why it doesn't work correctly otherwise!
Dim look_At_This As Variant
If match_Entire_Cell_Contents = True Then
look_At_This = xlWhole
Else
look_At_This = xlPart
End If
FirstOccurrence = 0 'Returns 0 if no match is found.
Dim FoundCell As Range
Dim myRange As Range
Dim LastCell As Range
Set myRange = Sheets(sheetName).Range(searchRange)
Set LastCell = myRange.Cells(myRange.Cells.Count)
Set FoundCell = myRange.Find(What:=search, after:=LastCell, MatchCase:=CaseSensitive, SearchDirection:=xlNext, lookat:=match_Entire_Cell_Contents, SearchOrder:=xlByRows, LookIn:=xlFormulas) 'xlFormulas , LookIn:=xlValues)
If Not FoundCell Is Nothing Then
FirstOccurrence = FoundCell.row
Else
'If there is no occurrence,
Exit Function
End If
End Function