Function PhanBoSoLuong(ByVal maxPhut#, ByVal Ngay, ByVal SoLuong, _
Chung As Range, DinhMuc As Range, May As Range, Rng As Range) As Variant
Dim sRow&, sCol&, i&, j&
Dim tMay$, tDinhMuc#, tSoLuong As Variant
Dim tmpChung$, tmpPhut#
sRow = Rng.Rows.Count: sCol = Rng.Columns.Count
tMay = May(sRow, 1).Offset(1).Value
tDinhMuc = DinhMuc(sRow, 1).Offset(1).Value
If Rng(1, sCol) < Ngay Then PhanBoSoLuong = "X": Exit Function
For j = 2 To sCol - 1
tSoLuong = Rng(sRow, j).Offset(1).Value
If IsNumeric(tSoLuong) Then SoLuong = SoLuong - tSoLuong
Next j
For i = 2 To sRow
If IsNumeric(Rng(i, sCol)) Then
If May(i, 1) = tMay Then
If Chung(i, 1) = Empty Then
maxPhut = maxPhut - Rng(i, sCol) * DinhMuc(i, 1)
Else
If tmpChung <> Chung(i, 1) Then
tmpChung = Chung(i, 1)
tmpPhut = 0
End If
If tmpPhut < Rng(i, sCol) * DinhMuc(i, 1) Then
tmpPhut = Rng(i, sCol) * DinhMuc(i, 1)
End If
If tmpChung <> Chung(i, 1).Offset(1) Then
maxPhut = maxPhut - tmpPhut
End If
End If
End If
End If
Next i
tSoLuong = maxPhut / tDinhMuc
If SoLuong > tSoLuong Then
PhanBoSoLuong = Round(tSoLuong, 6)
Else
PhanBoSoLuong = Round(SoLuong, 6)
End If
End Function