Quote:
Wow, thanks for the head start. I would have never found that on my
own. |
That's why Jesus created nerds.
Quote:
Is it getting complicated yet? |
No not yet!? ;-)
Alright, you'll have to modify this code as you did before to allow for form
controls, events, etc., but here it is:
Public Function GetDiscount(dblVolume As Double) As Double
Dim db As Database
Dim rec As DAO.Recordset
Dim dblRate() As Double
Dim dblBase() As Double
Dim dblTemp As Double
Dim i As Integer, j As Integer
Set db = CurrentDb()
'Set recordset to the Discount Table
Set rec = db.OpenRecordset("Discount")
i = 0
j = 0
With rec
'Populate recordset
.MoveLast
.MoveFirst
'Each record in this table represents a discount bracket (like a tax
'bracket.) Redimension arrays for all possible rates and bases
ReDim dblRate(0 To .RecordCount - 1)
ReDim dblBase(0 To .RecordCount - 1)
'Loop through all records
Do While Not .EOF
'Populate Arrays
dblRate(i) = .Fields("Discount")
dblBase(i) = GetBase(dblVolume, .Fields("Start"), .Fields("End"))
i = i + 1
.MoveNext
Loop
End With
'Calculate discount
For j = 0 To UBound(dblRate)
dblTemp = dblTemp + (dblBase(j) * dblRate(j))
Next
GetDiscount = dblTemp
'Clean up
CleanExit:
rec.Close
db.Close
Set rec = Nothing
Set db = Nothing
End Function
Private Function GetBase(ByVal dblVol As Double, _
ByVal dblstart As Double, ByVal dblEnd As Double) As Double
'This function computes the correct base upon which to apply rate.
GetBase = 0
Dim dblTemp As Double
'If Volume is below the beginning of the bracket, then base is zero
If dblVol < dblstart Then
Exit Function
End If
'If Volume is above the end of the bracket, then the base includes the
'entire range of the bracket.
If dblVol >= dblEnd Then
GetBase = dblEnd - dblstart
Exit Function
Else
'If Volume is somewhere in the middle of the braket's range, then the base
'is Volume minus the starting point of the bracket.
GetBase = dblVol - dblstart
End If
End Function
The above code is broken down into two functions. The first loops through
all discount brakets in the Discount table and assigns that Discount's rate
to an array containing all rates. Likewise, it assigns a base upon which to
apply the rate to an array containing all bases. The GetBase function calc
the base. See comments in that code for a detailed explanation of how it
works.
Johnny