1

Column A has numbers from 0 to 5. When there is a number greater than 0, I want it to generate that number of random numbers in the columns next to that cell.
For example if A4 = 3, then I want a random numbers in B4,C4 and D4.

I have the following code that works fine in picking up values over 0 and generating a random number between 200 and 300 but I am stuck on how to have it generate more than one. Can anyone point me in the right direction? thank you

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

3 Answers 3

3

You have your loops switched:

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

here's a formula approach

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.