根据列的input生成一系列随机数。 VBA Excel

列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 

你有你的循环切换:

 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 
 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 

这是一个公式的方法

 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