Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading