excel随机函数出来的数相加等于一个想要的固定值 比如 产生20个随机数想加等于200而且每个数都不大于3

问题描述:

excel随机函数出来的数相加等于一个想要的固定值 比如 产生20个随机数想加等于200而且每个数都不大于3
最好用VBA 错了 相加总数是50
1个回答 分类:综合 2014-12-07

问题解答:

我来补答
Option Explicit
Function getRandom(total As Integer, max As Integer, num As Integer) As Boolean
'total是最后要得到的总和,max是最大不能超过的数,num是产生多少个随机数
Dim ranNum As Single '随机数
Dim leftNum As Single '剩余数
Dim conNumTotal As Single '确定的剩余数
Dim i As Integer

'判断条件是否满足
getRandom = True
If max * num < total Then
'根本就不可能满足条件,直接退出
getRandom = False
Exit Function
End If

conNumTotal = 0

For i = 1 To num - 1 Step 1
DoEvents
Randomize '随机化
'很显然地所有的ranNum都满足小于max的条件
ranNum = Rnd() * max '产生随机数
'判断当前数据的合理性
leftNum = total - conNumTotal - ranNum
If max * (num - i) < leftNum Then
'无法满足基本要求,退回序列
i = i - 1
Else
'满足要求,继续
conNumTotal = conNumTotal + ranNum
Debug.Print ranNum
End If
'自行处理产生的ranNum
Next i
'最后一个随机数
ranNum = total - conNumTotal
Debug.Print ranNum
debug.print "over"
'由于最后一个数
End Function
Sub a()
getRandom 200, 11, 20
End Sub
再问: 怎么产生不了数据
再答: '判断条件是否满足 getRandom = True If max * num < total Then '根本就不可能满足条件,直接退出 getRandom = False Exit Function End If 你分别传入200 3 20 这就的确是无法产生数据的,3*20=60,怎么也不可能实现要求 上面列出的代码就是判断这种非常无理的请求的…… 你用50的话就使用 Sub a() getRandom 50, 11, 20 End Sub ……你不会是说你不知道在什么地方看debug.print出来的数据吧? 如果这样的话你把第一个 Debug.Print ranNum 改成: thisworkbook.worksheets(1).range("A" & i).formular1c1=rannum 把最后一个 Debug.Print ranNum 改成: thisworkbook.worksheets(1).range("A" & i).formular1c1=rannum
再问: 为什改成50还是出不来数呢
再答: 立即窗口里面有没有数? 还是什么都没有打出来? If max * num < total Then '根本就不可能满足条件,直接退出 getRandom = False Exit Function End If 新加一句: If max * num < total Then '根本就不可能满足条件,直接退出 getRandom = False debug.print "not match exit function" //这句 Exit Function End If
 
 
展开全文阅读
剩余:2000
下一页:立体几何 24题
也许感兴趣的知识