除了成員David Zemens給出的優秀答案,以下是用「純」Excel VBA編寫的通用函數,它不包含任何Excel工作表函數,也不包含Dictionary對象(re:CreateObject("Scripting.Dictionary"
)。
Option Explicit
'get N random integer numbers in the range from LB to UB, NO repetition
'general formula: Int ((UpperBound - LowerBound + 1) * Rnd + LowerBound)
Function RandomNumbers(LB As Integer, UB As Integer, N As Integer) As Variant
Dim I As Integer
Dim arrRandom() As Integer
Dim colRandom As New Collection
Dim colItem As Variant
Dim tempInt As Integer
Dim tempExists As Boolean
'check that ArraySize is less that the range of the integers
If (UB - LB + 1 >= N) Then
While colRandom.Count < N
Randomize
' get random number in interval
tempInt = Int((UB - LB + 1) * Rnd + LB)
'check if number exists in collection
tempExists = False
For Each colItem In colRandom
If (tempInt = colItem) Then
tempExists = True
Exit For
End If
Next colItem
' add to collection if not exists
If Not tempExists Then
colRandom.Add tempInt
End If
Wend
'convert collection to array
ReDim arrRandom(N - 1)
For I = 0 To N - 1
arrRandom(I) = colRandom(I + 1)
Next I
'return array of random numbers
RandomNumbers = arrRandom
Else
RandomNumbers = Nothing
End If
End Function
'get 5 Random numbers in the ranger 1...10 and populate Worksheet
Sub GetRandomArray()
Dim arr() As Integer
'get array of 5 Random numbers in the ranger 1...10
arr = RandomNumbers(1, 10, 5)
'populate Worksheet Range with 5 random numbers from array
If (IsArray(arr)) Then
Range("A1:A5").Value = Application.Transpose(arr)
End If
End Sub
功能
Function RandomNumbers(LB As Integer, UB As Integer, N As Integer)
返回N個隨機數的陣列中的範圍LB ... UB包含地不重複。
示例Sub GetRandomArray()
演示瞭如何獲得1到10範圍內的5個隨機數字並填充工作表範圍:它可以針對任何特定要求(例如PO需求中的1 ... 40中的8)進行自定義。
附錄A(大衛Ziemens提供)
或者,你可以不用依靠收集對象上都類似。構建一個分隔字符串,然後使用Split
函數將字符串轉換爲數組,然後將其返回給調用過程。
這實際上返回的數字爲String
,但這對於這個特殊的用例應該不重要,如果是這樣,可以很容易地進行修改。
Option Explicit
Sub foo()
Dim arr As Variant
arr = RandomNumbersNoCollection(1, 40, 6)
End Sub
'get N random integer numbers in the range from LB to UB, NO repetition
'general formula: Int ((UpperBound - LowerBound + 1) * Rnd + LowerBound)
Function RandomNumbersNoCollection(LB As Integer, UB As Integer, N As Integer)
Dim I As Integer
Dim numbers As String ' delimited string
Dim tempInt As Integer
Const dlmt As String = "|"
'check that ArraySize is less that the range of the integers
If (UB - LB + 1 >= N) Then
' get random number in interval
Do
Randomize
tempInt = Int((UB - LB + 1) * Rnd + LB)
If Len(numbers) = 0 Then
numbers = tempInt & dlmt
ElseIf InStr(1, numbers, tempInt & dlmt) = 0 Then
numbers = numbers & tempInt & dlmt
End If
Loop Until UBound(Split(numbers, dlmt)) = 6
numbers = Left(numbers, Len(numbers) - 1)
End If
RandomNumbersNoCollection = Split(numbers, dlmt)
End Function
有些這樣的感覺就像你剛做了OP的作業。我希望我在高中時認識你。 :)但是我會將這個頁面添加到我的收藏夾,因爲我可以看到使用這種變化的其他東西。 –
@ScottCraner是的,我可能做到了。雖然OP有一些努力,但這是一個相對簡單而有趣的問題:) –