根据列的输入生成一系列随机数。 VBA Excel
问题描述:
列A的数字从0到5.当数字大于0时,我希望它在该单元格旁边的列中生成该数量的随机数。
例如,如果A4 = 3,那么我需要一个在B4,C4和D4中的随机数。根据列的输入生成一系列随机数。 VBA Excel
我有以下的代码,它可以在拾取超过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
+0
感谢您的不同期待! – Pauliec
+0
不客气。感谢您的反馈意见 – user3598756
哈啊,这是有道理的(嫌头)非常感谢你! ! – Pauliec