VBA从数组中获取随机字符串

时间:2018-06-29 15:26:20

标签: excel vba excel-vba random

我试图能够从一个数组中返回一个字符串,该字符串将被放入用户窗体的标签中。我已经看到了很多东西,但是似乎没有一个起作用。我有一个名为Compliments的数组,我想拉出该数组的字符串之一并将其传递给我的label6,但是因为这是一个用户窗体,仅在工作表打开并瞬间打开时才会显示,因此我希望使其随机。每次有人打开工作表时,他们都会得到不同的称赞,以帮助他们开始新的一天。我的所有代码如下:

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

1 个答案:

答案 0 :(得分:6)

您可以在VBA中使用Rnd()函数生成一个随机数。通过一些数学运算,您可以强制其介于两个整数之间。在这种情况下,它将在0到Compliments数组的上限之间。像下面这样的东西应该起作用:

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