VBA程式設計問題?

2019-11-17 8:11 pm
之前有發問過 後來寫了一套程式

我想要讓他

在表格1-200 出現隨機5~10個 1~80的數字

然後201-400 出現10~15個

400~500 出現15~20個

寫出來如下

Function createRandonNumbers(ByVal j As Integer)

Dim list(1 To 80) As Integer

Dim i As Integer

Dim randomnumber As Long

For i = 1 To (5 + Rnd() * 5)

randomnumber = 1 + Rnd() * 79

Cells(j, i) = randomnumber

i = i - list(randomnumber)

list(randomnumber) = 1

Next

End Function

Function createRandonNumbers1(ByVal y As Integer)

Dim list(1 To 80) As Integer

Dim x As Integer

Dim randomnumber As Long

For x = 1 To (10 + Rnd() * 5)

randomnumber = 1 + Rnd() * 79

Cells(y, x) = randomnumber

x = x - list(randomnumber)

list(randomnumber) = 1

Next

End Function

Function createRandonNumbers2(ByVal b As Integer)

Dim list(1 To 80) As Integer

Dim a As Integer

Dim randomnumber As Long

For a = 1 To (15 + Rnd() * 5)

randomnumber = 1 + Rnd() * 79

Cells(b, a) = randomnumber

a = a - list(randomnumber)

list(randomnumber) = 1

Next

End Function

Sub main5到10()

Worksheets("工作表1").Range("A:Z").ClearContents

Dim j As Integer

For j = 1 To 200

Call createRandonNumbers(j)

Next

End Sub

Sub main10到15()

Worksheets("工作表1").Range("A:Z").ClearContents

Dim y As Integer

For y = 201 To 400

Call createRandonNumbers1(y)

Next

End Sub

Sub main15到20()

Worksheets("工作表1").Range("A:Z").ClearContents

Dim b As Integer

For b = 401 To 500

Call createRandonNumbers2(b)

Next

End Sub

但結果我案執行後 只出現了401~500的資料 請問是哪裡有錯?
更新1:

用你這方法做出來的 數字會重複欸 而且還是一樣 沒辦法同時全部出現1~500的 案執行後還是只有出現401~500 的資料

回答 (1)

2019-11-17 9:41 pm
參考
https://ithelp.ithome.com.tw/questions/10194111


Sub xx()
Dim mybag As New Collection
Cells.ClearContents
For j = 1 To 200 '執行次數
For i = 1 To 80
    mybag.Add (i)
Next
k = 1
For x = 1 To Int((6 * Rnd) + 5)
    R = Int(mybag.Count * Rnd()) + 1
    Cells(j, k).Value = mybag.Item(R)
    mybag.Remove (R) '亂數重複不重複出現
    k = k + 1
Next
Next




''第2段
.....
.....

End Sub


收錄日期: 2021-05-03 06:59:52
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20191117121140AA3VyM5

檢視 Wayback Machine 備份