vb新手 求各位帮忙看看代码
代码如下:Private Sub Command2_Click(Index As Integer)
Dim i As Integer, r As Integer
Dim colList As New Collection
Dim strSQL As String
Dim conn As New ADODB.Connection
Dim RS As New ADODB.Recordset
Dim db As String
db = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & App.Path & "\tuimag.mdb"
conn.Open db
On Error Resume Next 'Collection 添加重复的关键字(Key)会触发457错误,下面利用该错误避免重复数字
n = InputBox("输入n值")
If n > 45 Then Exit Sub
Randomize (Time)
Do Until n < 0
r = Int(Rnd * 45) + 1
colList.Add r, "a" & r '关键字只能是字符开头,所以加了个"a"
If Err.Number = 457 Then
Err.Clear '清空错误,本次获取数字失效
Else
n = n - 1 '没有错误,说明添加成功,这里要避免其他错误
End If
Loop
'构造查询字符串,将生成的数字组成列表
strSQL = "("
For i = 1 To colList.Count
strSQL = strSQL & colList(i) & ","
Next
Mid(strSQL, Len(strSQL), 1) = ")"
Text2.Text = strSQL
strSQL = "select * from stukq_math where StuNum in" & strSQL
'从数据库获取数据,只获取指定 stuNum 的记录,Conn 是 connection 对象,已经打开对应的数据库
RS.CursorLocation = adUseClient
RS.Open strSQL, conn, adOpenForwardOnly, adLockReadOnly, adCmdText
Set DataGrid1.DataSource = RS
DataGrid1.Refresh
End Sub
大致就是先产生n个1-45间的随机不重复随机整数,然后利用datagrid控件输出所有stu表中stuNum等于那些随机数的数据。
随机数产生是没有问题的,但datagrid始终显示不了数据。。。各位帮忙改下。感激不尽