Excel VBA SQL - multiple data sources -
i have simple problem cannot find answer to.
i have following sql:-
select filea in (select b fileb)
i attempting run in excel using vba.
the problem have filea table on as/400 , fileb table in excel spreadsheet. is, 2 different datasources. can't find way combine 2 datasources in 1 sql statement.
anybody got bright ideas.
the below example shows how data 2 excel workbooks within single sql query (since haven't got as/400 data source), , put result recordset worksheet. code placed in query.xlsm
:
option explicit sub sqlwhereintest() dim strconnection string dim strquery string dim objconnection object dim objrecordset object strconnection = _ "provider=microsoft.ace.oledb.12.0;" & _ "user id=admin;" & _ "data source='" & thisworkbook.fullname & "';" & _ "mode=read;" & _ "extended properties=""excel 12.0 macro;"";" strquery = _ "select * [sheet1$] " & _ "in '" & thisworkbook.path & "\src1.xlsx' " & _ "[excel 12.0;provider=microsoft.ace.oledb.12.0;mode=read;extended properties='hdr=yes;'] " & _ "where country in " & _ "(select countryfilter [sheet1$] " & _ "in '" & thisworkbook.path & "\src2.xlsx' " & _ "[excel 12.0;provider=microsoft.ace.oledb.12.0;mode=read;extended properties='hdr=yes;'])" set objconnection = createobject("adodb.connection") objconnection.open strconnection set objrecordset = objconnection.execute(strquery) recordsettoworksheet sheets(1), objrecordset objconnection.close end sub sub recordsettoworksheet(objsheet worksheet, objrecordset object) dim long objsheet .cells.delete = 1 objrecordset.fields.count .cells(1, i).value = objrecordset.fields(i - 1).name next .cells(2, 1).copyfromrecordset objrecordset .cells.columns.autofit end end sub
also there 2 workbooks data sources in same folder query.xlsm
.
src1.xlsx
containing customers:
src2.xlsx
:
the resulting worksheet follows:
it works on 64-bit version excel 2013 me. make compatible .xls
, excel 2003 (where provider ace.oledb.12.0
isn't installed) have replace provider=microsoft.ace.oledb.12.0;
provider=microsoft.jet.oledb.4.0;
, , in extended properties excel 12.0 macro;
/ excel 12.0;
excel 8.0;
. data source connection object isn't limited query.xlsm
file (see thisworkbook.fullname
part within strconnection
), code placed in. data source, compatible 1 of available providers, either file-based or server-based. find more connection strings data source on http://www.connectionstrings.com/
Comments
Post a Comment