View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Auric__ Auric__ is offline
external usenet poster
 
Posts: 538
Default Nearest one or two or three numbers in a row of data

tikrit wrote:

I have a problem today. I tried in different ways but could not solve
it.

Lest's say I have the following row of Data:

61 49 55 45 48 69 79 51

I need a code (Excel formula) that find the closest two or three numbers
to 50 but lower than 50 (which in this case are 49 48 and 45)

I will then add them to each other and put the result in a single cell

Notes : the data must be in Row. Mine is Excel 2010.


Try this:

Function ClosestTo(lowerThan As Range, what As Range, _
Optional ByVal numResults As Long)
If numResults < 1 Then numResults = 3
Dim cell As Range, L0 As Long, L1 As Long
ReDim closest(numResults - 1) As String

'Find the desired cells.
For Each cell In what
If (cell.Value < lowerThan.Value) Then
For L0 = 0 To numResults - 1
If Len(closest(L0)) Then
If (cell.Value Range(closest(L0)).Value) Then
For L1 = numResults - 1 To L0 + 1
closest(L1) = closest(L1 - 1)
Next
closest(L0) = cell.Address
Exit For
End If
Else
closest(L0) = cell.Address
Exit For
End If
Next
End If
Next

'Add them up.
For L0 = 0 To numResults - 1
If Len(closest(L0)) Then outP = outP + Range(closest(L0)).Value
Next

ClosestTo = outP
End Function

The first argument is the cell containing the value to check against. The
second arg is the range to check. The third (optional) arg is how many
results you want. (If not specified, or less than 1, defaults to 3.)

ClosestTo can be called either from VBA or within a cell. In VBA, call it
like this:
x = ClosestTo(Cells(1, 1), Range("A2:H2"))
x = ClosestTo(Cells(1, 1), Range("A2:H2"), 2)

In a cell, call it like this:
=ClosestTo(A1,A2:H2)
=ClosestTo(A1,A2:H2,2)

To check cells that aren't continguous, enclose the addresses with an
additional set of parentheses:
=ClosestTo(A1,(A2,C2,E2,G2))
=ClosestTo(A1,(A2,C2,E2,G2),2)

--
Nationality doesn't determine beauty.