A列的数字从0到5.当数字大于0时,我希望它在该单元格旁边的列中生成该数量的随机数。
例如,如果A4 = 3,那么我想要B4,C4和D4中的随机数。
我有以下代码可以正常工作,获取超过0的值并生成一个介于200和300之间的随机数,但我仍然坚持如何让它生成多个。 谁能指出我正确的方向?谢谢
Sub RandomNumbers()
Dim i As Integer
Dim j As Integer
Dim lastrow As Integer
lastrow = Range("a1").End(xlDown).Row
For j = 1 To 1
For i = 1 To lastrow
If ThisWorkbook.Sheets("LossFrequency").Cells(i, j).Value > 0 Then
ThisWorkbook.Sheets("LossFrequency").Cells(i, j + 1).Value = Int((300 - 200 + 1) * Rnd + 200)
Else: ThisWorkbook.Sheets("LossFrequency").Cells(i, j + 1).Value = 0
End If
Next i
Next j
End Sub
答案 0 :(得分:3)
你已经切换了你的循环:
Sub RandomNumbers()
Dim i As Integer
Dim j As Integer
Dim lastrow As Integer
lastrow = Range("a1").End(xlDown).Row
With ThisWorkbook.Sheets("LossFrequency")
For i = 1 To lastrow
If .Cells(i, 1).Value > 0 Then
For j = 1 To .Cells(i, 1).Value
.Cells(i, j + 1).Value = Int((300 - 200 + 1) * Rnd + 200)
Next j
Else
.Cells(i, 2).Value = 0
End If
Next i
End With
End Sub
答案 1 :(得分:2)
Sub RandomNumbers()
Dim i As Integer
Dim j As Integer
Dim lastrow As Integer
Dim iValue As Integer
Dim iColCount As Integer
j = 1
lastrow = Range("a1").End(xlDown).Row
For i = 1 To lastrow
iValue = ThisWorkbook.Sheets("LossFrequency").Cells(i, j).Value
If iValue > 0 Then
For iColCount = 1 To iValue
ThisWorkbook.Sheets("LossFrequency").Cells(i, iColCount + 1).Value = Int((300 - 200 + 1) * Rnd + 200)
Next iColCount
Else
ThisWorkbook.Sheets("LossFrequency").Cells(i, j + 1).Value = 0
End If
Next i
End Sub
答案 2 :(得分:2)
这是一个公式方法
Sub RandomNumbers()
Dim cell As Range
With ThisWorkbook.Sheets("LossFrequency")
For Each cell In .Range("A1", .Cells(.Rows.count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants, xlNumbers)
If cell.Value = 0 Then
cell.Offset(, 1).Value = 0
Else
cell.Offset(, 1).Resize(, cell.Value).FormulaR1C1 = "=RandBetween(300,200)"
End If
Next
End With
End Sub