首页 > 解决方案 > ADO 查询中缺少单元格

问题描述

我正在查询三个工作簿,每个工作簿都有三张工作表,并将它们整理成一个带有三个整理工作表的工作簿。

它运行;然而,每隔一段时间,就会有缺失的单元格。

我做了一些研究,有人说当您使用较旧的连接字符串时会发生这种情况。我不是。
其他人说当字符长度超过 255 时会发生这种情况。丢失的单元格是整数长度 6 或双精度长度 8。
其他人说,当查询有超过 65,535 行数据时会发生这种情况。我的每个查询最多有 3,000 行。

我在原始工作表中有相同数据的重复列,并且副本缺少与第一列不同的行。

在每个结果表的 6000 行中,只有 26 个零星单元格在第一张表的主列中是空白的;重复列中没有丢失任何内容。
第二张表的主列没有单元格丢失,但是重复列有大块单元格丢失,总共大约 500 个单元格。
第三张纸无动于衷。

作为一种解决方法,我运行一个循环检查空白单元格并从另一列复制它。

有没有办法让所有数据出现在查询中?

Option Explicit

Public Sub report_SourceDataFile()
    Dim connection As New ADODB.connection
    Dim rs As New ADODB.Recordset
    Dim wbSource As Workbook
    Dim strConn As String, strQuery As String, strPath As String
    Dim shtArr As Variant, shtElm As Variant
    Dim i As Long, j As Long, lastrow As Long

    Set wbSource = Workbooks.Add
    shtArr = Array("sht1", "sht2", "sht3")

    For i = 2018 To 2020
        strPath = "path" & i & ".xlsm"
        strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strPath & ";Extended Properties=""Excel 12.0;HDR=Yes;"";"
        connection.Open strConn

        For Each shtElm In shtArr
            wbSource.Sheets.Add(after:=wbSource.Sheets(wbSource.Sheets.Count)).Name = shtElm
            strQuery = "SELECT * FROM [" & shtElm & "$]"
            rs.Open strQuery, connection

            ' Write header
            If i = 2018 Then
                For j = 0 To rs.Fields.Count - 1
                    wbSource.Sheets(shtElm).Cells(1, j + 1).Value = rs.Fields(j).Name
                Next j
            End If

            lastrow = wbSource.Sheets(shtElm).Cells(wbSource.Sheets(shtElm).Rows.Count, 4).End(xlUp).Row
            wbSource.Sheets(shtElm).Cells(lastrow + 1, 1).CopyFromRecordset rs
            rs.Close
        Next shtElm

        connection.Close
    Next i
End Sub

标签: excelvbaado

解决方案


推荐阅读