从两个不同的来源过滤百万记录到100,000

时间:2014-12-24 16:49:06

标签: sql excel vba filter

我有一个项目,我想在Excel VBA中自动报告一组愚蠢的大数据。基本上我有一个1,000,000+记录数据库,我想从中提取~100,000条记录。我有100,000个项目的唯一方法是在excel表中,我无法将其转储到同一个数据库中以过滤或进入同一服务器上的临时表。 有没有办法将Excel电子表格值视为数据库并在VBA中的SQL查询中调用它?我不想使用循环,因为数据库响应已经足够糟糕了。

想法?

感谢。

编辑 - 我假设"循环不好"根据一条评论是不正确的。这是真的?循环访问ID必须轮询数据库100,000次,还是将其视为单个数据拉?

1 个答案:

答案 0 :(得分:1)

如果要使用类似SQL的语法在工作簿中查询,可以使用ADODB。

我已经包含了一个sub作为如何执行此操作的示例。你可以像下面这样打电话给那个小组:

Call queryTable("select top 100000 * from [Sheet6$A1:AI31]", range("Sheet5!A1"))

这将查询位于Sheet6$A1:AI31范围内的数据(第一行是标题),并将从左上角单元格Sheet5!A1开始转储数据。

Sub queryTable(sqlStr As String, destination As Range)
Dim strFile As String
Dim stADO As String
Dim cnt                 As ADODB.Connection
Dim recordcount         As Long
Dim fieldcount          As Long
Dim resultrange         As Range
Dim mydestination       As Range

strFile = ThisWorkbook.FullName

'connection string may need to be altered a little bit depending on your excel version
stADO = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
                            & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"

Set cnt = New ADODB.Connection

'Running query
    With cnt
        .CursorLocation = adUseClient
        .Open stADO
        .CommandTimeout = 0
        Set rst = .Execute(sqlStr)
    End With

Set mydestination = destination.Cells(1, 1).Offset(1, 0)

'Copying data (not headers) to destination
mydestination.CopyFromRecordset rst

'Setting some important variables
recordcount = rst.recordcount
fieldcount = rst.Fields.Count

Set range_collection = Range(mydestination.Cells(1, 1).Offset(-1, 0),                  mydestination.Cells(1, 1).Offset(recordcount - 1, fieldcount - 1))

'Copying the headers
For i = 0 To fieldcount - 1
mydestination.Cells(1, 1).Offset(-1, i).value = rst.Fields(i).name
Next i


'Closing everything down
cnt.Close
Set cnt = Nothing


End Sub