Excel 2007 Visual Basic: minimum values
Here's sample sheet:
ColA, ColB, ColC
A, 0.2, 10% A, 0.3, 1% A, 0.5, 6% B, 0.4, 9% B, 0.3, 8% B, 1.2, 40%I have to find minimum value in ColB for specified value in ColA, then check if ColC in this row is greater than 15%. If so - return value of ColB. If not, find next minimum value and sum with previously found value, then again check if sum is greater than 15%, and so on.. Return last summed value from ColB.
Example (for ColA="A"):
1. find minimum value in ColB (cell: B2, value 0.2) 2. check if value in ColC in this row (cell: C2, value 10%) is greater than 15% (not met!) sum with previously val = 0 + 10% = 10% 3. take next minimum value in ColB (cell: B3, value 0.3) 4. check >15% condition -> (cell: C3, value 1%) sum with previously val = 10% + 1% = 11% (still not met) 5. take next minimum value in ColB (cell: B4, value 0.5) 6. check >15% condition -> (cell: C4, value 6%) sum with previously va开发者_如何学Gol = 11% + 6% = 17% (condition met) 7. The last cell we summed was C4, so we return value from ColB in this row - 0.5(Answer for "B" is 0.4)
I'd like to ask for any hints to solve this problem. Hope it's clear ;)
Here's the prototype of my function
Function foo(ColA As String) As Integer
Function Foo(rng As Range, ColA As String, Target As Variant) As Variant
Dim Dat() As Variant
Dim r As Long, c As Long
Dim sm As Variant
' Get Data from sheet
Dat = rng.Value2
' Sort DAT on column B
' <sort code here>
sm = 0#
' Loop through rows
For r = LBound(Dat, 1) To UBound(Dat, 1)
' If Column 1 matches
If Dat(r, 1) = ColA Then
' sum of column 3
sm = sm + Dat(r, 3)
' If target reached
If sm >= Target Then
' Return result
Foo = Dat(r, 2)
Exit Function
End If
End If
Next
' Target not reached
Foo = "No Answer"
End Function
Call function like this (replace $A$1:$C$6 to suit your sheet)
=Foo($A$1:$C$6,"A",15%)
精彩评论