我試圖使用ADO liblary對sql語句進行操作的宏,但實際上它只返回6559條記錄,而我的一個表有72k條記錄。 爲什麼?爲什麼ADO VBA代碼只返回6559條記錄?
最近,我注意到,實際上我的代碼並沒有返回6559,而是行號 - 65537.所以當我減少工作表中的行數到72092時,我甚至得到更少的行(6550)。
我注意到的另一件事是rs.RecordCount返回「-1」。
這是我子程序的代碼。它有三個參數:sql語句(sqlstmt),目標工作表名稱(sheet_name)和目標範圍(destination1)。
'subprocedure that execute sql statements and save resault in given worksheet
Public Sub sql_query(ByVal sqlstmt As String, ByVal sheet_name As String, ByVal destination1 As String)
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim connstring As String
Dim qt As QueryTable
Dim tw_path As String
Dim is_name As Boolean
Dim sh As Worksheet
'''making sheet if it doesn't exist
is_name = False
For Each sh In ThisWorkbook.Worksheets
If sh.Name = sheet_name Then is_name = True
Next
If is_name = False Then ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)).Name = sheet_name
''' connection
tw_path = ThisWorkbook.path & "\" & ThisWorkbook.Name
connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & tw_path & ";Extended Properties=Excel 8.0;Persist Security Info=False"
Set conn = New ADODB.Connection
conn.ConnectionString = connstring
conn.Open
'''executing statement
Set rs = New ADODB.Recordset
rs.Source = sqlstmt
rs.ActiveConnection = conn
rs.Open
'''saving records
ThisWorkbook.Worksheets(sheet_name).Activate
Set qt = Worksheets(sheet_name).QueryTables.Add(Connection:=rs, Destination:=Range(destination1))
qt.Refresh
'''end
If rs.State <> adStateClosed Then rs.Close
conn.Close
If Not rs Is Nothing Then Set rs = Nothing
If Not conn Is Nothing Then Set conn = Nothing
Set qt = Nothing
End Sub
感謝您的幫助
這是我的經驗,ADO不會總是加載記錄集,除非強制。在rs.Open後添加rs.MoveLast以強制它讀取所有記錄 – 2013-04-10 15:28:30
謝謝,但實際上它dooes沒有幫助:( – PtrZlnk 2013-04-11 09:27:47