使用Sub Procedure调用随机数并将字符串显示到标签

时间:2015-12-03 16:17:41

标签: vba

我试图获取一个随机数来生成并获取所述随机数,以通过子过程向标签显示分配给该数字的特定文本行。

如果这更容易:

  1. 生成随机数1到5
  2. 使用子程序调用随机数
  3. 将字符串显示到与该随机数连接的标签。
  4. 我会展示我的代码,这样你们就知道我的方向是什么以及它是否正确。

    Public Class Form1
    
    Private Sub btnInsult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsult.Click
        Dim strInsult As String
        Dim intNumber As Integer
        Randomize()
        intNumber = Int((5 - 1 + 1) * Rnd() + 1)
    
    End Sub
    Sub showInsult()
    
    End Sub
    
    End Class
    

    它真的不是很多,我认为我朝着正确的方向前进。请问我是否需要进一步澄清事情。

1 个答案:

答案 0 :(得分:0)

我有一段用于生成随机消息的类似代码。 与上面的代码不同,它是在表单模块中编写的,而不是类1,并打印到文本框而不是标签。

我不确定
  

将标签显示为标签

您实际上是指更改实际标签标题。如果是,请改用showInsultEx sub。它适合您的需求。我希望这会有所帮助。

Private arrInsults() As Variant
Private nInsultCount As Integer

Private Sub Insult_InitRepertoire()
    'init the insult array
    arrInsults = Array( _
    "Insult 1", _
    "Insult 2", _
    "Insult 3", _
    "Insult 4", _
    "Insult 5")

    nInsultCount = UBound(arrInsults) - LBound(arrInsults) + 1
End Sub

Private Sub showInsult()
    'init the insult array if empty
    If nInsultCount = 0 Then Insult_InitRepertoire

    'get a random entry from the insult table
    'and print it in the text field
    Randomize
    Me.TextBox1.Text = arrInsults(LBound(arrInsults) + Int(Rnd() * nInsultCount))
End Sub

Private Sub btnInsult_Click()
    'invoke the pseudo-random inslut generator
    showInsult
End Sub

Private Sub UserForm_Initialize()
    'prevent user input
    Me.TextBox1.Locked = True
End Sub

Private Sub showInsultEx()
    Dim nId As Integer

    'init the insult array if empty
    If nInsultCount = 0 Then Insult_InitRepertoire

    'get a random entry from the insult table
    'and print it in the text field
    Randomize
    nId = LBound(arrInsults) + Int(Rnd() * nInsultCount)

    'get a control associated with the insult number
    'change its caption to the generated text
    'you'll have to make sure to number the controls
    'according to the array indices
    Me.Controls("Label" & nId).Caption = arrInsults(nId)
End Sub