3

How do I make the following code input either "Jack" or "John" randomly in cell A1? Currently, the result is always "2":

Sub RandomNames ()

Dim UserNames(1 To 2) As String

UserNames(1) = "Jack"
UserNames(2) = "John"

Range("A1").Value = Application.WorksheetFunction.RandBetween(LBound(UserNames), UBound(UserNames))

End Sub
6
  • 1
    Thanks, just a typo. Commented Sep 8, 2017 at 14:39
  • 1
    With your code now, without the typo, I get 1 and 2 pretty evenly. Commented Sep 8, 2017 at 14:44
  • 1
    BTW: the formula version: =CHOOSE(RANDBETWEEN(1,2),"Jack","John") Commented Sep 8, 2017 at 14:47
  • Thanks a lot, but I needed names, not numbers. Commented Sep 8, 2017 at 14:58
  • I was just stating that your comment Currently, the result is always "2" is a little misleading as to your problem, as the code will return both 1 and 2. Commented Sep 8, 2017 at 15:03

1 Answer 1

4

Try using randbetween on the array.

Range("A1").Value = UserNames(Application.RandBetween(LBound(UserNames), UBound(UserNames)))
Sign up to request clarification or add additional context in comments.

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.