excel如何在某一区间生成不重复的随机整数?

2025年03月18日 09:43
有1个网友回答
网友(1):

以取30项总和为50000且不重复的整数为例

'自定义公式-按ALT+F11-点击插入-点击模块
Sub 随机取不重复数()
a = Split(随机取数(30), "|", -1, 1)
For i = 1 To 29
Cells(i, 2) = 1000 + a(i)
Next
Cells(30, 2) = 50000 - WorksheetFunction.Sum(Range("b1:b29"))
End Sub
Function 随机取数(num As Integer) As String
Dim a
For j = 100 To 1100
t = t & "|" & j
Next
t = Right(t, Len(t) - 1)
a = Split(t, "|", -1, 1)
Dim i As Integer
Randomize
Dim Index As Integer
Dim Text As String
Dim arU As Integer
arU = UBound(a)
If num > arU + 1 Then num = arU + 1
For i = 1 To num
Index = Int(Rnd * arU)
Text = Text & "|" & a(Index)
a(Index) = a(arU)
arU = arU - 1
Next
随机取数 = Text
End Function