如果您想使用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
我不清楚你想要做什么:你的标题谈论2个不同的数据源,但你的问题只提到1个数据源。你想要做什么来加入一个100K excel记录与一个1000K记录在数据库中? –
Excel 100k列表是一个数据源... 1m记录位于DB2数据库中。 100k ID驻留在1m记录中,我正在寻找一种方法从DB2记录集中提取100K记录。我认为循环会非常重要,但从下面的评论我可能是错的。我可以通过任何方式从1m DB2记录中获取Excel Sheet中的100k ID,而无需将所有记录从DB2加载到Excel中,这是我需要做的。 – JustMe
我建议你的db2数据库中的存储过程接受一个ID值列表作为输入参数。根据您的数据库中的要求处理值。这将是棘手的,因为你可能会遇到某种最大允许数量。然后运行适当的查询。在vba中,读取带有id字段的列,调用存储过程,并对查询结果进行一些操作。 –