Place one of three values in a cell at radom

I had a code that would place 1 or 2 values in a cell at random (The values were either "SF" or "BM") and I used to do it this way

Worksheets("Sheet1").Range("A1").Value = IIf(Rnd() > 0.5, "BM", "JC")

The problem is that I want to add a new third value "KS" and doing the following doesn’t work

Worksheets("Sheet1").Range("A1").Value = IIf(Rnd() > 0.5, "BM", "JC", "KS")

How can I place one of these 3 values at random in a cell?

>Solution :

here is a way I would do it

Dim value As String

Select Case Int(Rnd() * 3)
    Case 0
        value = "BM"
    Case 1
        value = "JC"
    Case 2
        value = "KS"
End Select

Worksheets("Sheet1").Range("A1").Value = value

I generate a random integer between 0 and 2 using Int(Rnd() * 3), and then use a Select Case statement to assign the corresponding value ("BM", "JC", or "KS") to the value variable. Finally, the code places the value in cell A1 of Sheet1.

Leave a Reply