给你个例子 将这个放到模块中 Public Function ExecuteSQL(ByVal sql As String, MsgString As String) As ADODB.Recordset Dim cnn As ADODB.Connection Dim rst As ADODB.Recordset Dim sTokens() As String On Error GoTo ExecuteSQL_Error sTokens = Split(sql) Set cnn = New ADODB.Connection cnn.Open "Provider=sqloledb;Data Source=服务器名称;Initial Catalog=数据库名称;User Id=sa;Password=;" If InStr("INSERT,DELETE,UPDATE", UCase$(sTokens(0))) Then cnn.Execute sql MsgString = sTokens(0) & "query successful" Else Set rst = New ADODB.Recordset rst.Open Trim$(sql), cnn, adOpenKeyset, adLockOptimistic
Set ExecuteSQL = rst MsgString = "查询到" & rst.RecordCount & "条纪录" End IfExecuteSQL_Exit: Set rst = Nothing Exit Function Set cnn = Nothing ExecuteSQL_Error: MsgString = "查询错误:" & Err.Description Resume ExecuteSQL_Exit End Function '在窗体中用法Dim mrc As ADODB.Recordset Dim TxtSQL As String Dim msgtext As String Private Sub cmdSearch_Click() TxtSQL = "select * from RH_kcyjz where yj_time like '%" & sydate & "%'" Set mrc = ExecuteSQL(TxtSQL, msgtext) do while not mrc msgbox rs(0) rs.movnext loop End Sub
将这个放到模块中
Public Function ExecuteSQL(ByVal sql As String, MsgString As String) As ADODB.Recordset
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sTokens() As String
On Error GoTo ExecuteSQL_Error
sTokens = Split(sql)
Set cnn = New ADODB.Connection
cnn.Open "Provider=sqloledb;Data Source=服务器名称;Initial Catalog=数据库名称;User Id=sa;Password=;"
If InStr("INSERT,DELETE,UPDATE", UCase$(sTokens(0))) Then cnn.Execute sql
MsgString = sTokens(0) & "query successful" Else Set rst = New ADODB.Recordset
rst.Open Trim$(sql), cnn, adOpenKeyset, adLockOptimistic
Set ExecuteSQL = rst
MsgString = "查询到" & rst.RecordCount & "条纪录" End IfExecuteSQL_Exit:
Set rst = Nothing
Exit Function
Set cnn = Nothing
ExecuteSQL_Error:
MsgString = "查询错误:" & Err.Description
Resume ExecuteSQL_Exit
End Function
'在窗体中用法Dim mrc As ADODB.Recordset
Dim TxtSQL As String
Dim msgtext As String
Private Sub cmdSearch_Click()
TxtSQL = "select * from RH_kcyjz where yj_time like '%" & sydate & "%'"
Set mrc = ExecuteSQL(TxtSQL, msgtext)
do while not mrc
msgbox rs(0)
rs.movnext
loop
End Sub