【问题标题】:Why ADO VBA code returns only 6559 records?为什么 ADO VBA 代码只返回 6559 条记录?
【发布时间】: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 以强制它读取所有记录。
  • 谢谢,但实际上它并没有帮助:(

标签: vba ado adodb


【解决方案1】:

我猜您使用的是 excel 2003 或更早版本,在这种情况下,工作表最多有 65,536 行。我会把它放在评论而不是答案中,但我还差 1 个代表能够发表评论:(。对不起

【讨论】:

  • 感谢您的回答。实际上我正在使用 excel 2007 和 ADO 6.0 库,我的一张表确实有 72 k 行:) 但是,可能不可能使用超过 65536 行的表,因为当我将这张表拆分为两张较小的表并只使用SQL UNION 命令它工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多