Function Find_Range(Find_Item As Variant, _
Search_Range As Range, _
Optional LookIn As Variant, _
Optional LookAt As Variant, _
Optional MatchCase As Boolean) As Range
Dim c As Range
If IsMissing(LookIn) Then LookIn = xlValues 'xlFormulas
If IsMissing(LookAt) Then LookAt = xlPart 'xlWhole
If IsMissing(MatchCase) Then MatchCase = False
With Search_Range
Set c = .Find( _
What:=Find_Item, _
LookIn:=LookIn, _
LookAt:=LookAt, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=MatchCase, _
SearchFormat:=False)
If Not c Is Nothing Then
Set Find_Range = c
FirstAddress = c.Address
Do
Set Find_Range = Union(Find_Range, c)
Set c = .FindNext(c)
Loop While Not c Is Nothing And c.Address <> FirstAddress
End If
End With
End Function
Function Middle(r As Range) As Variant
Dim i As Long, j As Long
If r.Columns.Count > 1 Then
Middle = [#N/A]
Exit Function
End If
i = r.Row
j = r.Rows.Count
Middle = Cells(i + (j - 1) / 2, r.Column).Address
End Function
Sub FindMiddleCell()
Dim MyRange1, MyRange2, MyRange3, MyRange4 As Range
Dim MiddleCell1, MiddleCell2, MiddleCell3, MiddleCell4 As Variant
'Using the Find_Range function from above to find the numbers 1,2,3 and 4 within the range M1:M100 and return the range
'The "MyRange" variables are then used in other places in the code as well as here.
Set MyRange1 = Find_Range(1, Range("M1:M100"), xlFormulas, xlWhole)
Set MyRange2 = Find_Range(2, Range("M1:M100"), xlFormulas, xlWhole)
Set MyRange3 = Find_Range(3, Range("M1:M100"), xlFormulas, xlWhole)
Set MyRange4 = Find_Range(4, Range("M1:M100"), xlFormulas, xlWhole)
'Using your Function to find the middle cell address.
'Altered the final line of your Function code to return an absolute reference.
MiddleCell1 = Middle(Range(MyRange1.Address))
MiddleCell2 = Middle(Range(MyRange2.Address))
MiddleCell3 = Middle(Range(MyRange3.Address))
MiddleCell14 = Middle(Range(MyRange4.Address))
'The following test works with MiddleCells 1,2 and 3 but not 4
MsgBox MiddleCell4
End Sub