VBA“;行集不支持向后提取";错误。游标类型已调整
使用以下代码,我打开了与SQLServer的连接,并将结果直接放入数组中。我的问题是,我得到了一个错误的行数,我需要重拨我的数组。我得到的错误在下面指示的行上,如下所示 “行集不支持向后提取” 我能找到的所有答案都表明光标类型是问题所在,但据我所知,我已经改变了这一点。很抱歉代码太长,我觉得最好还是先把开头放进去VBA“;行集不支持向后提取";错误。游标类型已调整,vba,excel,Vba,Excel,使用以下代码,我打开了与SQLServer的连接,并将结果直接放入数组中。我的问题是,我得到了一个错误的行数,我需要重拨我的数组。我得到的错误在下面指示的行上,如下所示 “行集不支持向后提取” 我能找到的所有答案都表明光标类型是问题所在,但据我所知,我已经改变了这一点。很抱歉代码太长,我觉得最好还是先把开头放进去 Function ConnectServer() As String() 'Working SQL Server connection Dim conn As ADODB.Conne
Function ConnectServer() As String()
'Working SQL Server connection
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim strSqlQuery As String
Dim iCols As Long
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=wait;" & _
"Initial Catalog=what;" & _
"User Id=foo;" & _
"Password=bar;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
rs.CursorType = adOpenDynamic
rs.CursorLocation = adUseClient
conn.CommandTimeout = 50
' Open the connection and execute.
conn.Open sConnString
' Debug.Print strSqlQuery
Set rs = conn.Execute("SELECT DISTINCT a FROM b")
' Check we have data.
If Not rs.EOF Then
'*****************Problem here********************
rs.MoveLast
Debug.Print rs.RecordCount
'Read into array and cleanup...
End If
End Function
我不认为这是这个问题的重复:
因为我已经将答案合并到代码中,问题仍然存在。问题是由使用conn.Execute填充记录集引起的。将记录集的activeconnection设置为ADODB.Connection并使用记录集的open方法将解决此问题
Function ConnectServer() As String()
'Working SQL Server connection
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim strSqlQuery As String
Dim iCols As Long
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=wait;" & _
"Initial Catalog=what;" & _
"User Id=foo;" & _
"Password=bar;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
conn.ConnectionString = sConnString
conn.Open
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = conn
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.Source = "SELECT * FROM b"
.Open
End With
' Check we have data.
If Not rs.EOF Then
rs.MoveLast
Debug.Print rs.RecordCount
'Read into array and cleanup...
End If
End Function
可以使用Recordset.GetRows()填充数组。没必要把它调暗 是否要将所有记录添加到一个数组中?是的,我需要对记录进行计数以重新分配数组,然后我会将它们添加到记录集的
源部分,因为它们有一个复杂的并集,而此方法似乎不适用于我。同样的声明和一切。另外,P.S.GetRows()
非常好,直到您的数据集变得巨大。遗憾的是,我的数据集超出了GetRows()的工作范围。