乐于分享
好东西不私藏

《哆哆Excel》随机凑数工具(附代码)

《哆哆Excel》随机凑数工具(附代码)
Excel插件设计,好玩
两个,上图,上代码
一、随机凑数工具1(范围)
1.界面
2.部分代码
    ' 按权重比例生成随机数    Private Function GenerateNumbersByWeight(targetValue As Double, weights() As Double, isInteger As Boolean) As Double()        Dim count As Integer = weights.Length        Dim numbers(count - 1) As Double        ' 为每个权重添加少量随机波动(可选)        For i As Integer = 0 To count - 1            ' 基础值按权重计算            Dim baseValue As Double = targetValue * weights(i)            ' 添加 ±10% 的随机波动            Dim fluctuation As Double = baseValue * 0.1 * (random.NextDouble() * 2 - 1)            Dim randomValue As Double = baseValue + fluctuation            If isInteger Then                numbers(i) = Math.Round(randomValue)            Else                numbers(i) = Math.Round(randomValue, 2)            End If        Next        ' 调整第一个数确保总和等于目标值        Dim actualSum As Double = numbers.Sum()        Dim adjustment As Double = targetValue - actualSum        If isInteger Then            numbers(0) = Math.Round(numbers(0) + adjustment)        Else            numbers(0) = Math.Round(numbers(0) + adjustment, 2)        End If        Return numbers    End Function
二、随机凑数工具2(方式)
1.界面
2.部分代码
 ' ================================================================ ' 模式一:几个和=原数 ' 使用"前瞻法":每次生成时预留后续数的空间,确保最后一个数合法 ' ================================================================ Private Function GenerateBySum(targetValue As Double, splitCount As Integer,                                minVal As Double, maxVal As Double,                                isInteger As BooleanAs Double()     Dim numbers(splitCount - 1As Double     Dim sumSoFar As Double = 0     Dim remainingCount As Integer = splitCount     For i As Integer = 0 To splitCount - 1         remainingCount -= 1         ' 剩余数至少需要的最小总和         Dim needMin As Double = remainingCount * minVal         ' 剩余数至多能接受的最大总和         Dim needMax As Double = remainingCount * maxVal         ' 当前数可取范围         Dim low As Double = Math.Max(minVal, targetValue - sumSoFar - needMax)         Dim high As Double = Math.Min(maxVal, targetValue - sumSoFar - needMin)         If low > high Then             ' 约束冲突,取中点逼近             low = minVal             high = maxVal         End If         If isInteger Then             low = Math.Ceiling(low)             high = Math.Floor(high)             If low > high Then low = high             numbers(i) = Math.Round(low + random.NextDouble() * (high - low))         Else             numbers(i) = Math.Round(low + random.NextDouble() * (high - low), 2)         End If         sumSoFar += numbers(i)     Next     Return numbers End Function