如果只是为了实现功能,那就ChatGPT吧,下列示例ChatGPT给出的代码:
Private Sub Command1_Click()
Dim arrNames() As String
Dim i As Integer
Dim strName As String
Dim intIndex As Integer
Dim strOutput As String
'Read names from file
Open "1.TXT" For Input As #1
Do Until EOF(1)
Line Input #1, strName
If strName <> "" Then
ReDim Preserve arrNames(i)
arrNames(i) = strName
i = i + 1
End If
Loop
Close #1
'Randomly sort names
Randomize
For i = LBound(arrNames) To UBound(arrNames)
intIndex = Int((UBound(arrNames) - i + 1) * Rnd + i)
strName = arrNames(i)
arrNames(i) = arrNames(intIndex)
arrNames(intIndex) = strName
Next i
'Display names with index
For i = LBound(arrNames) To UBound(arrNames)
strOutput = strOutput & i + 1 & ". " & arrNames(i) & vbCrLf
Next i
Text1.Text = strOutput
End Sub
建议这节增加一行命令
'Read names from file
Open "1.TXT" For Input As #1
Do Until EOF(1)
Line Input #1, strName
strName = trim(strName) '清前后空格,防出错
If strName <> "" Then
ReDim Preserve arrNames(i)
arrNames(i) = strName
i = i + 1
End If
Loop
Close #1
Private Sub Command1_Click()
'读取1.TXT文件中的姓名
Dim names() As String
Dim i As Integer
Open "1.TXT" For Input As #1
Do Until EOF(1)
ReDim Preserve names(i)
Line Input #1, names(i)
i = i + 1
Loop
Close #1
'随机排序
Randomize
Dim j As Integer
Dim temp As String
For i = 0 To UBound(names)
j = Int(Rnd() * (UBound(names) - i + 1)) + i
temp = names(i)
names(i) = names(j)
names(j) = temp
Next i
'显示结果
Text1.Text = ""
For i = 0 To UBound(names)
Text1.Text = Text1.Text & i + 1 & ". " & names(i) & vbCrLf
Next i
End Sub