EXCEL中VBA如何执行SQL SERVER 2005存储过程?
EXCEL 2003中VBA如何执行SQL SERVER 2005存储过程?
我下面的代码执行非常正常, 可以把SQL SERVER中表的数据很好地取出填入单元格里
问: 我有个没有任何输入输出参数的SQLSERVER存储过程名叫chaos, 该过程最后返回一个结果集,我如何将这结果集存入rs?
我试过各种方法, 都出错:3704 对象关闭时, 不允许操作.
Public conn As ADODB.Connection
Public rs As ADODB.Recordset
Public Cmd1 As ADODB.Command
Private Sub CommandButton1_Click()
Call CreateConnect
End Sub
Private Sub CommandButton2_Click()
Call CloseConnect
End Sub
Public Sub CreateConnect()
'================================
'
' 创建新连接
'
'================================
Dim ConnStr As String
Dim sHost As String
Dim sDatabaseName As String
Dim sUserName As String
Dim sPassword As String
sHost = "tang" 'Sqlsever服务器IP地址或计算机名
sDatabaseName = "test" '连接的数据库名
sUserName = "sa" '登录用户名
sPassword = "nevertell" '登录密码
On Error GoTo ERR:
'vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
'
'定义连接字符串
'
ConnStr = ""
ConnStr = ConnStr & "Provider=SQLOLEDB;"
ConnStr = ConnStr & "Password=" & sPassword & ";"
ConnStr = ConnStr & "User ID=" & sUserName & ";"
ConnStr = ConnStr & "Initial Catalog=" & sDatabaseName & ";"
ConnStr = ConnStr & "Data Source = " & sHost
'^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
'建立连接
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
With conn
.ConnectionString = ConnStr
.Open
End With
MsgBox "连接成功", vbOKOnly + vbInformation
strSql = "SELECT * FROM ProblemPool"
rs.Open strSql, conn
Set sht = ThisWorkbook.Worksheets("sheet1")
i = 1
Do While Not rs.EOF '当数据指针未移到记录集末尾时,循环下列操作
sht.Cells(i, 1) = rs("id") '把当前记录的字段1的值保存到sheet1工作表的第i行第1列
sht.Cells(i, 2) = rs("question") '把当前字段2的值保存到sheet1工作表的第i行第2列
rs.MoveNext '把指针移向下一条记录
i = i + 1 'i加1,准备把下一记录相关字段的值保存到工作表的下一行
Loop
Exit Sub
ERR:
' MsgBox "连接错误", vbOKOnly + vbCritical
End Sub
Public Sub CloseConnect()
'================================
'
' 断开连接
'
'================================
On Error GoTo ERR:
conn.Close
Set conn = Nothing
MsgBox "成功断开连接", vbOKOnly + vbInformation
Exit Sub
ERR:
MsgBox "断开连接错误", vbOKOnly + vbCritical
End Sub
[解决办法]
貌似是数据库没连上打开
SQL服务器没搞过,网上搜一下,应该是ConnStr还缺少什么参数
[解决办法]
MARK,先帮顶下
[解决办法]
既是报"3704 对象关闭时, 不允许操作",这里报的对象是否Recordset,还是conn本身在操作时就已经Close???直接msgbox断点检查先
楼主存储过程如何写的?
可试着改strSql = "SELECT * FROM ProblemPool"为
strSql="exec chaos"
[解决办法]
你不定义command对象
直接用
set rs=conn.execute("exec chaos")
试试
我也不太确定问题出在哪里!
[解决办法]
set rs=conn.execute("exec 对应数据库..chaos")