【发布时间】:2018-08-15 13:46:42
【问题描述】:
我找到了以下代码,并想让它生成 (3) 个唯一随机数,存储在 X、Y 和 Z 变量中。有人可以帮我修改它以添加 (2) 更多存储为变量的随机数,并在代码中指定这些随机数的范围吗?
Sub RandomizeArray(ArrayIn As Variant)
Dim X As Long, RandomIndex As Long, TempElement As Variant
Static RanBefore As Boolean
If Not RanBefore Then
RanBefore = True
Randomize
End If
If VarType(ArrayIn) >= vbArray Then
For X = UBound(ArrayIn) To LBound(ArrayIn) Step -1
RandomIndex = Int((X - LBound(ArrayIn) + 1) * Rnd + LBound(ArrayIn))
TempElement = ArrayIn(RandomIndex)
ArrayIn(RandomIndex) = ArrayIn(X)
ArrayIn(X) = TempElement
Next
Else
'The passed argument was not an array, so put error handler here, such as . . .
Beep
End If
End Sub
我的原始代码需要随机数是唯一的:
Sub FormatSuperProjectHeadings()
Dim r As Byte, g As Byte, b As Byte
Dim r2 As Byte, g2 As Byte, b2 As Byte
Dim spcolor As Integer
Dim vR(), n As Integer
'Clear Cells
n = 3000
ReDim vR(1 To n)
For i = 1 To n
r = WorksheetFunction.RandBetween(0, 127)
g = WorksheetFunction.RandBetween(0, 127)
b = WorksheetFunction.RandBetween(0, 127)
r2 = r + 127
g2 = g + 127
b2 = b + 127
vR(i) = RGB(r2, g2, b2)
Next i
Application.ScreenUpdating = False
Dim MyCell As Range
With Sheets(1) 'Projects Sheet
For Each MyCell In .Range("Y5:Y" & .Range("Y" & .Rows.Count).End(xlUp).Row)
If MyCell = "Super Project" Then
MyCell.EntireRow.Interior.Color = vR(WorksheetFunction.RandBetween(1, n))
MyCell.Offset(, -22).Font.Bold = True
End If
Next
End With
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
这段代码似乎过于复杂,只能创建 3 个唯一的随机数...
-
为什么不创建一个单独的函数来创建一个随机数,并简单地为其分配任意数量的变量呢?此外,您声明
RanBefore然后立即对其进行逻辑测试。为什么?你可以完全跳过那部分,直接做ranBefore = True // Randomize,不是吗? -
我是 VBA 新手,这段代码不是我目前使用的,但它让我开始使用“唯一值”功能。我编辑了我的原始帖子以显示我的代码。