Search code examples
vbaexceldistributionranking

VBA distribute values based on ranking


trying to finish a VBA that processes every 3 rows at a time. using the order of the rank column, distribute the values accordingly to the next three rows without each cell exceeding the max value of 62 and prioritizing the highest rank.

sample data:

enter image description here

here's what i have so far:

max_value = 62
For irow = 2 To 80 Step 3

    set_value = .Cells(irow, 2).Value

    'if value less than max, then assign value to highest rank
    If set_value < max_value Then
        toprank_value = .Range(.Cells(irow, 1), .Cells(irow + 3, 1)).Find(what:="1", LookIn:=xlValues).Address

        'assign value to rank of 1
        toprank_value.Offset(0, 2).Value = set_value

        GoTo NextIteration

    'if not, distribute values across next 3 rows based on rank not going over max of 62
    Else

        'NEED HELP FOR CODE HERE
        'NEED HELP FOR CODE HERE

    End If

NextIteration:
    Next

Thanks for any nudge to the right direction or if clarification is needed.


Solution

  • Assuming your value to distribute is always in the first of the 3 rows. Its ugly but seems to work.

    Sub distrib()
    
    Set R1 = ActiveSheet.UsedRange 'Edit range if other data in sheet
    T1 = R1
    
    M = 62
    
    For i = 2 To UBound(T1)
        If T1(i, 2) > 0 Then
            V = T1(i, 2)
            If V <= M Then
                For j = i To i + 2
                    If T1(j, 1) = 1 Then
                        T1(j, 3) = V
                    Else
                        T1(j, 3) = 0
                    End If
                Next j
            Else
                A = M
                V = V - M
                If V > M Then
                    B = M
                    V = V - M
                    If V > M Then
                        C = M
                    Else
                        C = V
                    End If
                Else
                    B = V
                    C = 0
                End If
                For j = i To i + 2
                    Select Case T1(j, 1)
                        Case Is = 1
                            T1(j, 3) = A
                        Case Is = 2
                            T1(j, 3) = B
                        Case Is = 3
                            T1(j, 3) = C
                    End Select
                Next j
            End If
        End If
    Next i
    
    For i = 2 To UBound(T1)
        Cells(i, 3) = T1(i, 3)
    Next i
    
    End Sub