Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA get random string from array

Tags:

random

excel

vba

I am trying to be able to return a string from an array that will be put into a label in a userform. I've seen a lot of things for this, but none of them seem to work. I have an array named Compliments that I want to pull one of the strings for that array and pass it through to my label6 but because this is a userform that only shows up when the sheet is opened and is opened momentarily I want to be able to make it random. Each time someone opens the sheet they will get a different compliment to help start their day. My code for everything is below:

Private Sub UserForm_Activate()
    TextBox1.Value = Date
    TextBox2.Value = Time
    TextBox3.Value = MainMenu.TextBox1.Value
    Label6.Caption = "RANDOM ARRAY GOES HERE"

    Application.Wait (Now + TimeValue("00:00:05"))

    Welcome.Hide
End Sub

Private Sub UserForm_Initialize()
    Me.StartUpPosition = 0
    Me.Top = (Application.Height / 2) - Me.Height / 2
    Me.Left = (Application.Width / 2) - Me.Width / 2

    Compliments = Array("Good Morning, You are Beautiful Today", _
        "I think you're pretty awesome", "That outfit looks great on you", _
        "You're a great engineer", "You rock Dude", "Nobody can get you down", _
        "Your makeup is spot on")
End Sub
like image 812
Stacie Avatar asked Jun 12 '26 23:06

Stacie


1 Answers

You can use the Rnd() function in VBA to generate a random number. With some math you can force it to be between two integers. In this case it will be between 0 and the upper bound of your Compliments array. Something like the following should work:

Function Compliments()
    'Function to return the array
    Compliments = Array("Good Morning, You are Beautiful Today", _
            "I think you're pretty awesome", "That outfit looks great on you", _
            "You're a great engineer", "You rock Dude", "Nobody can get you down", _
            "Your makeup is spot on")
End Function

Private Sub UserForm_Activate()
    TextBox1.Value = Date
    TextBox2.Value = Time
    TextBox3.Value = MainMenu.TextBox1.Value

    randArrIndex = Int ((Ubound(Compliments) +  1) * Rnd )
    Label6.Caption = Compliments(randArrIndex)

    Application.Wait (Now + TimeValue("00:00:05"))

    Welcome.Hide
End Sub

Private Sub UserForm_Initialize()
    Me.StartUpPosition = 0
    Me.Top = (Application.Height / 2) - Me.Height / 2
    Me.Left = (Application.Width / 2) - Me.Width / 2        
End Sub
like image 96
JNevill Avatar answered Jun 14 '26 13:06

JNevill