Im试图获得一个要生成的随机数,并使用所述随机数通过子过程将分配给该数字的某行文本显示给标签。
如果这更容易的话:
- 生成从1到5的随机数
- 使用子过程调用随机数
- 显示连接到该随机数的标签的字符串
我会展示我的代码,让你们知道我的方向是什么,以及它是否正确。
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
这真的不多,我认为我正朝着正确的方向前进。请问我你是否需要更多的澄清。
我有一段类似的代码用于生成随机消息。与上面的代码不同,这是在表单模块中编写的,而不是在类模块中,并打印到文本框中,而不是标签中。我不确定是否通过
显示字符串到标签
你实际上是指更改一个实际的标签标题。如果是,则使用showInsultEx
子。就在这里,根据您的需要进行调整。我希望这能有所帮助。
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