所以我有一个按钮可以随机选择一个1到100范围内的数字并放在一个单元格中:
Public Sub RangeValue()
Dim i As Long
Static n As Long, s As String
Const MIN = 1, MAX = 100, OUT = "L10", DEL = "."
Randomize
Do
i = Rnd * (MAX - MIN) + MIN
If 0 = InStr(s, i & DEL) Then
n = n + 1: s = s & i & DEL
Range(OUT) = i
If n > MAX - MIN Then n = 0: s = ""
Exit Do
End If: DoEvents
Loop
End Sub
我希望它现在从该范围中选择2个数字并放入两个单元格。我试过了:
Public Sub RangeValue()
Dim i As Long
Static n As Long, s As String
Const MIN = 1, MAX = 100, OUT = "L10""L11", DEL = "."
Randomize
Do
i = Rnd * (MAX - MIN) + MIN
If 0 = InStr(s, i & DEL) Then
n = n + 1: s = s & i & DEL
Range(OUT) = i
If n > MAX - MIN Then n = 0: s = ""
Exit Do
End If: DoEvents
Loop
End Sub
但它不起作用。目标是选择2个数字并放入2个单元格中,并且在完成所有100个数字之前不要重复它们。
答案 0 :(得分:0)
我没有密切关注你的代码,但同样你也可以尝试下面的代码,它更易于维护,并且会产生类似的结果。
Sub RandomValues()
With Range("L10:L11")
.Formula = "=RANDBETWEEN(1,100)"
.Value = .Value
End With
End Sub
答案 1 :(得分:0)
怎么样:
Public arr(1 To 100) As Variant
Sub ButtonCode()
If arr(1) = "" Then
For I = 1 To 100
arr(I) = I
Next I
Call Shuffle(arr)
Range("L10").Value = arr(1)
Else
N = Application.WorksheetFunction.Count(Range("L10:L" & Rows.Count))
Range("L10").Offset(N) = arr(N + 1)
End If
End Sub
Public Sub Shuffle(InOut() As Variant)
Dim I As Long, J As Long
Dim tempF As Double, Temp As Variant
Hi = UBound(InOut)
Low = LBound(InOut)
ReDim Helper(Low To Hi) As Double
Randomize
For I = Low To Hi
Helper(I) = Rnd
Next I
J = (Hi - Low + 1) \ 2
Do While J > 0
For I = Low To Hi - J
If Helper(I) > Helper(I + J) Then
tempF = Helper(I)
Helper(I) = Helper(I + J)
Helper(I + J) = tempF
Temp = InOut(I)
InOut(I) = InOut(I + J)
InOut(I + J) = Temp
End If
Next I
For I = Hi - J To Low Step -1
If Helper(I) > Helper(I + J) Then
tempF = Helper(I)
Helper(I) = Helper(I + J)
Helper(I + J) = tempF
Temp = InOut(I)
InOut(I) = InOut(I + J)
InOut(I + J) = Temp
End If
Next I
J = J \ 2
Loop
End Sub
此代码会将值添加到以 L10 为单位的列表中,而不重复。
修改#1:强>
这应该更好:
Dim arr(1 To 100) As Variant
Dim clicks As Integer
Sub ButtonCode2()
If arr(1) = "" Then
For I = 1 To 100
arr(I) = I
Next I
Call Shuffle(arr)
Range("L10").Value = arr(1)
Range("L11").Value = arr(2)
clicks = 3
Else
Range("L10").Value = arr(clicks)
Range("L11").Value = arr(clicks + 1)
clicks = clicks + 2
End If
End Sub
(将Shuffle代码保留原样)