VBA运行时错误3704与Excel中的记录集

时间:2014-04-07 21:01:47

标签: sql sql-server excel vba

美好的一天。

当这段代码点击"虽然不是objMyRecordset.EOF",我收到运行时错误3704.除此之外,当我将鼠标悬停在" objMyRecordset"部分" strPSTPath = CStr(objMyRecordset(" PSTPath"))",我看到错误开始" objMyRecordSet(PS ... =

我的SQL查询在SQL Server管理工作室中使用时工作正常。在遇到有问题的线路时,错误立即发生。我逐行逐步完成了代码。任何想法将不胜感激。谢谢。

Sub Button3_Click()

'******
'Variables
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset

'Open connection
objMyConn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=XXXX;Data Source=XXXX"
objMyConn.Open

'Set and execute SQL command
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = "<Valid SQL Command removed for public code display>"
objMyCmd.CommandType = adCmdText

'Open recordset
Set objMyRecordset.Source = objMyCmd
objMyRecordset.Open objMyCmd


While Not objMyRecordset.EOF

    strPSTPath = CStr(objMyRecordset("PSTPath"))
    MsgBox strPSTPath

    objMyRecordset.MoveNext
Wend

End Sub

3 个答案:

答案 0 :(得分:0)

试试这个:

Sub Button3_Click()

Dim SQL As String, strPSTPath As String
Dim objMyConn, objMyRecordset

    Set objMyConn = New ADODB.Connection
    Set objMyRecordset = New ADODB.Recordset

    objMyConn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;" & _
          "Persist Security Info=False;Initial Catalog=XXXX;Data Source=XXXX"

    SQL = "<Valid SQL Command removed for public code display>"

    objMyRecordset.Open SQL, objMyConn

    While Not objMyRecordset.EOF
        strPSTPath = CStr(objMyRecordset("PSTPath"))
        MsgBox strPSTPath
        objMyRecordset.MoveNext
    Wend

End Sub

答案 1 :(得分:0)

我使用VBA和ADODB已经有一段时间了,但我相信你需要执行命令对象而不是打开记录集对象:

set objMyRecordset = objMyCmd.Execute

看看这个link

答案 2 :(得分:0)

追踪问题。此特定服务器上的SQL版本的连接字符串不正确。将连接字符串更改为:

Driver = {SQL Server Native Client 11.0}; Server = XXXX; Database = XXXX; Trusted_Connection = yes;

现在一切正常。