VBA 从列中添加值直到达到特定数字

VBA Adding values from a column until it reaches a certain number

我有一列的值从“R85”到“R193”。在上一列中,我为这些值命名,从“Q85”到“Q193”。我希望它一个一个地添加,直到它达到“I2”中的指定数字 我的想法是,我希望它添加数字,直到它达到接近 I2 值 (<=) 的数字,比方说 420,然后给我另一个单元格中的值的输出。 更复杂的部分是我需要 Q85 中的名称和它在 R 列上计算的最后一个值。 如果有人可以提供帮助,我将不胜感激!我到处搜索,找不到任何可以适应这个想法的东西。谢谢!

考虑以下用户定义函数:

Public Function SumUntil(rng As Range, lim As Variant) As Variant
    Dim r As Range, tot As Variant
    tot = 0
    
    For Each r In rng
        tot = tot + r.Value
        If tot > lim Then
            sumuntil = tot - r.Value
            Exit Function
        End If
    Next r
    
    sumuntil = tot
End Function

在上面的例子中,函数returns求A列前四项的总和