MyHanhCB
New Member
- Joined
- Feb 20, 2023
- Messages
- 30
- Office Version
- 2016
- Platform
- Windows
Hello everyone in the forum.
I have the following code that randomly changes the value contained in an array. But I think it's still not optimized.
Looking forward to more optimal solutions from professional programmers to consult and learn more about vba excel. Thank you very much.
I have the following code that randomly changes the value contained in an array. But I think it's still not optimized.
Looking forward to more optimal solutions from professional programmers to consult and learn more about vba excel. Thank you very much.
VBA Code:
Function ShuffleArray(arr As Variant) As Variant
Dim j%, i%, randomIndex%, dict As New Dictionary, myarr As Variant
Randomize
ReDim myarr(1 To UBound(arr, 1), 1 To UBound(arr, 2))
For j = LBound(arr, 1) To UBound(arr, 1)
randomIndex = Int((UBound(arr, 1) - LBound(arr, 1) + 1) * Rnd + LBound(arr, 1))
If Not dict.Exists(randomIndex) Then
dict.Add randomIndex, randomIndex
tiepRndIx:
For i = LBound(arr, 2) To UBound(arr, 2)
myarr(j, i) = arr(randomIndex, i)
Next i
Else
tiepRndIx1:
randomIndex = Int((UBound(arr, 1) - LBound(arr, 1) + 1) * Rnd + LBound(arr, 1))
If Not dict.Exists(randomIndex) Then
dict.Add randomIndex, randomIndex
GoTo tiepRndIx
Else
GoTo tiepRndIx1
End If
End If
Next j
ShuffleArray = myarr
End Function