如果单元格是特定值,我想使用VBA在2个值之间分配一个随机数。我在1到12之间有40个随机生成的数字,然后我想为这40个数字中的每一个分配两个值之间的随机数,但这两个值取决于数字是否为1,2,3,... ,12。我的代码现在看起来像这样但是出来的数字并不总是在我给出的限制之间。怎么了?
Sub measurepoints()
Dim i As Integer
Dim j As Integer
For i = 2 To 41
Cells(i, 1).Value = "=RANDBETWEEN(1,12)"
Next i
For j = 2 To 41
If Cells(j, 1).Value = 1 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,2)"
ElseIf Cells(j, 1).Value = 2 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,2)"
ElseIf Cells(j, 1).Value = 3 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,8)"
ElseIf Cells(j, 1).Value = 4 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,8)"
ElseIf Cells(j, 1).Value = 5 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,8)"
ElseIf Cells(j, 1).Value = 6 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,8)"
ElseIf Cells(j, 1).Value = 7 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,4)"
ElseIf Cells(j, 1).Value = 8 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,2)"
ElseIf Cells(j, 1).Value = 8 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,8)"
ElseIf Cells(j, 1).Value = 10 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,10)"
ElseIf Cells(j, 1).Value = 11 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,4)"
ElseIf Cells(j, 1).Value = 12 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,8)"
End If
Next j
End Sub
你有一个错字:
ElseIf Cells(j, 1).Value = 8 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,2)"
ElseIf Cells(j, 1).Value = 8 Then
Cells(j, 2).Value = "=RANDBETWEEN(1,8)"
无需VBA:
=RANDBETWEEN(1,INDEX({2,2,8,8,8,8,4,2,8,10,4,8},A1))
应该做你想做的事
要重新计算工作表中的所有功能,请按F9
。