Private Sub Command1_Click()
Dim names(1 To 5) As String ' 假设输入5个姓名
names(1) = "张三"
names(2) = "李四"
names(3) = "王五"
names(4) = "赵六"
names(5) = "钱七"
' 随机排序
Dim i As Integer, j As Integer
Dim temp As String
For i = 1 To 5
j = Int(Rnd() * 5) + 1
temp = names(i)
names(i) = names(j)
names(j) = temp
Next i
' 显示结果
Dim result As String
For i = 1 To 5
result = result & i & ":" & names(i) & vbCrLf
Next i
MsgBox result
End Sub
以下是一个简单的VB程序,实现了您所需的功能:
Private Sub btnSort_Click()
Dim names() As String
Dim i As Integer, j As Integer
Dim temp As String
'将输入的姓名按逗号分隔成数组
names = Split(txtNames.Text, ",")
'使用冒泡排序算法对姓名进行随机排序
For i = LBound(names) To UBound(names) - 1
For j = i + 1 To UBound(names)
If Rnd() < 0.5 Then
temp = names(i)
names(i) = names(j)
names(j) = temp
End If
Next j
Next i
'将排序后的姓名显示在屏幕上
For i = LBound(names) To UBound(names)
lstNames.AddItem names(i)
Next i
End Sub
Private Sub Command1_Click() Dim Count As Long, P As Long Dim Names() As Variant Dim Index() As Long
Names() = Array("A", "B", "C", "D", "E") Count = UBound(Names) Call GetRandoms(Count, Index()) For P = 0 To Count Debug.Print Names(Index(P)), Index(P) Next Erase Names(), Index() End Sub
Private Sub GetRandoms(ByVal Count As Long, Randoms() As Long) Dim iRnd As Long, P As Long Dim Exists() As Byte
ReDim Exists(Count) As Byte, Randoms(Count) As Long VBA.Randomize Do iRnd = Int((Count + 1) * VBA.Rnd()) If Exists(iRnd) = 0 Then Exists(iRnd) = 1 Randoms(P) = iRnd P = P + 1 End If Loop Until P > Count Erase Exists() End Sub