vb点名程序 随机点名不重复

算法:

1.将姓名都装入一个数组
2.记录下课随机的数量a,默认为数组长度
3.随机产生0~a的一个整数i
4.将数组arr(i)写入文件,同时将arr(i)和arr(a)交换,并且a--
5.重复执行3

 代码实现:

Option Explicit
Dim arr
Dim a As Integer
'初始化
Private Sub Form_Load()
    arr = Split("A001,A002,A003,A004,A005,A006", ",")
    a = UBound(arr)
End Sub
'点一次,随机一个出来
Private Sub Command1_Click()
    Dim i As Integer, intRnd As Integer, strTmp As String
    
    If a = -1 Then
        MsgBox "所有成员都随机过一次了!", vbExclamation
        Exit Sub
    End If
    
    Randomize
    intRnd = Int(Rnd * a)
    
    Me.Print "索引:" & intRnd, arr(intRnd), "提取前:" & Join(arr, ",") & " 参与随机" & a + 1 & "个", '输出并写入文件
    Open "结果.txt" For Append As #1
    Print #1, arr(intRnd)
    Close #1
    
    strTmp = arr(intRnd)
    arr(intRnd) = arr(a)
    arr(a) = strTmp
    a = a - 1
    Me.Print "提取后:" & Join(arr, ",") & " 剩余" & a + 1 & "个"
End Sub

运行结果:

vb点名程序 随机点名不重复_第1张图片

你可能感兴趣的:(练手)