为什么ADO VBA代码只返回6559条记录?

时间:2013-04-10 15:24:29

标签: vba ado adodb

我尝试使用带有ADO liblary的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

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我猜你使用的是excel 2003或以前的版本,在这种情况下,工作表最多有65,536行。我会把它放在评论中而不是答案中,但我只有1个代表能够发表评论:(。抱歉