[QUOTE=olives;3609]...but now I want to move data around and I think the reference to cell A1 is hindering me. Is there any way to make the formula and/or the code more 'generic' and have it search the next two adjacent columns to where I place the formula instead of always placing the number I want compared to in A1?
[QUOTE]
Okay, I think this will work the way you want, but note that the argument list to the function is completely different. First I'll give you the code, then I'll explain how to use it.
Code:
Function Largest(CompareValue As Double, TopLeftNumber As Range) As Variant
Dim X As Long, Index As Long, TestValue As Variant, Source As Variant, Results As Variant
Source = TopLeftNumber.Resize(Cells(Rows.Count, TopLeftNumber.Column).End(xlUp).Row - TopLeftNumber.Row + 1, 2)
ReDim Results(1 To UBound(Source), 1 To 1)
For X = 1 To UBound(Source)
If Source(X, 1) < CompareValue Then
Index = Index + 1
Results(Index, 1) = Source(X, 2)
End If
Next
Largest = WorksheetFunction.Large(Results, Application.Caller.Row - TopLeftNumber.Row + 1)
End Function
The first instance of this UDF must be placed on the same row as the first (topmost) number in your two columns of numbers. So, if your two columns of numbers were in C3:D100, the first instance of the formula must be placed in a cell on Row 3 (it does not have to be adjacent to the two columns of numbers). Now, for the arguments. The first argument is the value you want to compare (what used to be in A1 originally). You can specify it as a constant or a cell reference (but if you specify it as a cell reference, then the row number must be absolute (that is, there needs to be a $ sign in front of the number) so it won't change as the UDF is copied down. The second argument is a reference to the top left cell of the two columns of numbers being compared and the row number must also be absolute (that is, there needs to be a $ sign in front of the number) so it won't change as the UDF is copied down. So, if the two columns of numbers were in C3:D100, and the comparison number were 100, then the formula would look like this...
=Largest(100,C$3)
On the other hand, if your compare value was placed in F2, then the formula would look like this...
=Largest(F$2,C$3)
Note you do not specify the full range on that second argument, only the top left cell address... the code will calculate the row containing the last value for the two columns of numbers on its own.
Does this modification do what you want?
Bookmarks