我有一个ADODB记录集,用于从Excel工作表中的视图加载数据。该视图位于MS SQL数据库中。它运行完美几个月,但由于几天记录集总是空的,所以我没有得到任何结果。经过漫长的一天搜索www后,我发现任何原因,因为我使用x32 Excel并且视图中有太多数据。所以我在两个查询中分离了该过程。这有很大帮助,宏观再次完美运行。昨天同样的错误再次出现,所以我开始再次拆分程序。但现在记录集仍然是空的。我不知道任何理由。我测试了它只有十行视图的选择,这运行,但如果我想获得1000行记录集再次为空。有人知道这个问题的原因吗?所有查询都会给出我想要在数据库中拥有的结果,这样它们就可以了。
这是我的代码:
Sub doStuff()
Dim sqlStatement(9) As String
Dim lrow As Long
'... other variables
sqlStatement(1) = "Select * from db.View1 where location like 'forest'"
'... other sqlStatements
For i = 0 To UBound(sqlStatement)
Call loadData(sqlStatement, lrow)
Next i
End Sub
Sub loadData(sqlStatement As String, lastrow As Long)
Dim sqlServer As String
Dim dbName As String
sqlServer = "MSSQLSERVER"
dbName = "database"
On Error Resume Next
Dim con As Object
Set con = CreateObject("ADODB.Connection")
con.Open _
"Provider = sqloledb;" & _
"Data Source=" & sqlServer & ";" & _
"Initial Catalog=" & dbName & ";" & _
"User ID=user1;" & _
"Password=abcde;"
Dim rst As Object
Set rst = CreateObject("ADODB.Recordset")
With rst
.ActiveConnection = con
.Open sqlStatement , con, adLockReadOnly
ws.Activate
If lastrow = 1 Then
For col = 0 To .Fields.Count - 1
ws.Cells(1, col + 1).Value = .Fields(col).Name
Next
End If
ws.Activate
ws.Cells(lastrow+1,1).CopyFromRecordset rst
.Close
End With
con.Close
Set rst = Nothing
Set con = Nothing
End Sub