【发布时间】:2013-04-15 13:01:27
【问题描述】:
我尝试使用 ADO 库制作与 sql 语句一起操作的宏,但实际上它只返回 6559 条记录,而我的一张表有 72k 条记录。 为什么?
最近,我注意到,实际上我的代码并没有返回 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 以强制它读取所有记录。
-
谢谢,但实际上它并没有帮助:(