我需要生成幾組亂數,我的代碼的最小作業示例如下:
Sub Macro1()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Dim RA1 As Variant
Dim RA2 As Variant
Dim RA3 As Variant
Dim RA4 As Variant
ReDim RA1(1 To 63)
ReDim RA2(1 To 63)
ReDim RA3(1 To 63)
ReDim RA4(1 To 63)
For i = 1 To 1000
Rnd (-1)
Randomize i
For j = 1 To 63
RA1(j) = Rnd
Next j
Rnd (-2)
Randomize i
For k = 1 To 63
RA2(k) = Rnd
Next k
Rnd (-3)
Randomize i
For l = 1 To 63
RA3(l) = Rnd
Next l
Rnd (-4)
Randomize i
For m = 1 To 63
RA4(m) = Rnd
Next m
With Sheets("Economic Assumptions")
.Range("B10:BL10").Value = RA1
.Range("B11:BL11").Value = RA2
.Range("B12:BL12").Value = RA3
.Range("B13:BL13").Value = RA4
.Calculate
End With
Next i
End Sub
然而,雖然 RA1 是唯一的,但我發現我在 RA2、RA3 和 RA4 中的亂數在每個i. 換句話說,我的代碼給了我 RA1 <> RA2 = RA3 = RA4。這是為什么?我認為改變引數RND會改變亂數的種子?特別是,我需要 RA1、RA2、RA3 和 RA4 對每個 i 都有自己的一組亂數,但是當我重新運行整個程序時,我每次都應該得到相同的亂數。我該如何調整我的代碼來實作這一目標?
編輯
經過一些頭腦風暴和猜測和檢查作業后,以下代碼可以解決問題!
子宏1()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Dim RA1 As Variant
Dim RA2 As Variant
Dim RA3 As Variant
Dim RA4 As Variant
ReDim RA1(1 To 63)
ReDim RA2(1 To 63)
ReDim RA3(1 To 63)
ReDim RA4(1 To 63)
For i = 1 To 1000
Rnd (-1)
Randomize i
For j = 1 To 63
RA1(j) = Rnd
Next j
For k = 1 To 63
RA2(k) = Rnd
Next k
For l = 1 To 63
RA3(l) = Rnd
Next l
For m = 1 To 63
RA4(m) = Rnd
Next m
With Sheets("Economic Assumptions")
.Range("B10:BL10").Value = RA1
.Range("B11:BL11").Value = RA2
.Range("B12:BL12").Value = RA3
.Range("B13:BL13").Value = RA4
.Calculate
End With
Next i
End Sub
它也更短更甜。我非常高興 :)
uj5u.com熱心網友回復:
您可以分配給一個陣列,將陣列洗牌 x 次,保存到其他陣列,啞到作業表。通過限制與作業表的互動次數,這也應該更快:
Option Explicit
Sub xx()
Dim arr, nrOfsets As Long
arr = WorksheetFunction.RandArray(1, 63)
nrOfsets = 4
Dim arr2, j As Long, i As Long
ReDim arr2(1 To nrOfsets, 1 To UBound(arr))
For j = 1 To nrOfsets
For i = 1 To UBound(arr)
arr2(j, i) = arr(i)
Next i
arr = Resample(arr):
Next j
Dim startrow As Long, startcol As Long
startrow = 10: startcol = 2
With Sheet3
.Range(.Cells(startrow, startcol), .Cells(startrow - 1 nrOfsets, startcol - 1 UBound(arr2, 2))) = arr2
End With
End Sub
Function Resample(data_vector As Variant) As Variant()
'source: https://stackoverflow.com/questions/61020724/shuffle-an-array-in-vba
Dim shuffled_vector() As Variant
shuffled_vector = data_vector
Dim i As Long
For i = UBound(shuffled_vector) To LBound(shuffled_vector) Step -1
Dim t As Variant
t = shuffled_vector(i)
Dim j As Long
j = Application.RandBetween(LBound(shuffled_vector), UBound(shuffled_vector))
shuffled_vector(i) = shuffled_vector(j)
shuffled_vector(j) = t
Next i
Resample = shuffled_vector
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335705.html
