VBA產生隨機亂數設計問題?

2019-11-19 3:06 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~500筆的資料嗎

回答 (1)

2019-11-19 10:27 pm
✔ 最佳答案
Range("A:Z").ClearContents

改成只清除自己的範圍而不是全部都清空
Range("A1:Z200").ClearContents
Range("A201:Z400").ClearContents
Range("A401:Z500").ClearContents


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

檢視 Wayback Machine 備份