更好的随机,不重复,按顺序与Excelmacros

我一直在这个项目上工作了一段时间,并且在各个方面都有各种各样的帮助(多年来没有触及代码)

我创build了一个彩票生成器,并且我终于快要完成了,但是我的随机需要一些工作,并且我想按照连字符分隔的升序显示数字,如下面的示例没有括号:“ 24" 年12月16日

目前我的代码在一行中的三列上放置了一个不同的随机数(1-24),并重复,直到循环完成。 代码应该将列最小化为1“彩票”列而不是三个。

任何想法,我怎么能做到这一点? 我现在的代码如下:

Sub New_Entry() Dim strPlayer As String, strTick As Integer, i As Integer, j As Integer strPlayer = InputBox("Input Player Name") strTick = InputBox("How many tickets?") i = Cells(Rows.Count, 1).End(xlUp).Row + 1 For i = i To i + strTick - 1 Cells(i, 1).Value = strPlayer For j = 2 To 4 Cells(i, j).Value = Int((24 - 1 + 1) * Rnd + 1) Next j Next i End Sub 

如果你不想重复只是testing数字是否已经在数组中,如果是真的,然后计算一个新的随机数(这个代码是为6个中奖号码写的):

 Sub New_Entry() Dim strPlayer As String, strTick As Integer, i As Integer, j As Integer Dim win_tkt As Variant Dim number_to_find As Integer strPlayer = InputBox("Input Player Name") strTick = InputBox("How many tickets?") ReDim win_tkt(5) 'how many numbers are extracted -1 i = Cells(Rows.Count, 1).End(xlUp).Row + 1 For i = i To i + strTick - 1 Cells(i, 1).Value = strPlayer win_tkt(0) = Int((24 - 1 + 1) * Rnd + 1) For j = 2 To 6 'from 2nd winning number to last winning number number_to_find = Int((24 - 1 + 1) * Rnd + 1) Do While IsInArray(number_to_find, win_tkt) = True number_to_find = Int((24 - 1 + 1) * Rnd + 1) Loop win_tkt(j - 1) = number_to_find Next j Call sort_array(win_tkt) Cells(i, 2).Value = Join(win_tkt, "-") Next i End Sub Function IsInArray(find_number As Integer, arr As Variant) As Boolean IsInArray = (UBound(Filter(arr, find_number)) > -1) End Function Sub sort_array(arr As Variant) Dim strTemp As String Dim i As Long Dim j As Long Dim lngMin As Long Dim lngMax As Long lngMin = LBound(arr) lngMax = UBound(arr) For i = lngMin To lngMax - 1 For j = i + 1 To lngMax If arr(i) > arr(j) Then strTemp = arr(i) arr(i) = arr(j) arr(j) = strTemp End If Next j Next i End Sub 

以下可能会帮助你:

 Function LotteryTicket() As String Dim i As Long Dim nums(1 To 3) As Integer Dim A(1 To 3) As Variant With Application.WorksheetFunction Do While True For i = 1 To 3 nums(i) = .RandBetween(1, 24) Next i For i = 1 To 3 A(i) = .Small(nums, i) Next i If A(1) <> A(2) And A(2) <> A(3) Then LotteryTicket = Join(A, "-") Exit Function End If Loop End With End Function 

它使用一个简单的碰撞和错过的方法来获得不同的数字。 1-24中3个随机select的数字不同的概率是P(24,3)/24^3 = 87.8%所以期望通过外部循环的次数小于2。

像这样testing:

 Sub test() Dim i As Long For i = 1 To 10 Cells(I,1).Value = LotteryTicket() Next i End Sub 

运行后,输出看起来像(假设单元格被格式化为文本,所以Excel不解释为date):

 1-7-10 1-17-23 8-14-15 8-12-24 2-14-17 4-7-14 5-6-23 16-20-21 4-10-24 6-11-15