[使用VBA执行SQL.doc
文本预览下载声明
A、根据本工作簿的1个表查询求和写法范本
Sub 查询方法一()
Set CONN = CreateObject(ADODB.Connection)
CONN.Open provider=microsoft.jet.oledb.4.0;extended
properties=excel 8.0;data source= ThisWorkbook.FullName
sql = select 区域,存货类, sum(代销仓入库数量),sum(代销仓出库数量),sum(日报数量)from
[sheet4$a:i] where 区域= [b3] and month(日期)=
Month(Range(F3)) group by 区域,存货类
Sheets(sheet2).[A5].CopyFromRecordset CONN.Execute(sql)
CONN.Close: Set CONN = Nothing
End Sub
-----------------
Sub 查询方法二()
Set CONN = CreateObject(ADODB.Connection)
CONN.Open dsn=excel files;dbq= ThisWorkbook.FullName
sql = select 区域,存货类, sum(代销仓入库数量),sum(代销仓出库数量),sum(日报数量)from
[sheet4$a:i] where 区域= [b3] and month(日期)=
Month(Range(F3)) group by 区域,存货类
Sheets(sheet2).[A5].CopyFromRecordset CONN.Execute(sql)
CONN.Close: Set CONN = Nothing
End Sub
**************************************************************************************************
B、根据本工作簿2个表的不同类别查询求和写法范本
Sub 根据入库表和回款表的区域名和月份分别求存货类发货数量和本月回款数量查询()
Set conn = CreateObject(adodb.connection)
conn.Open provider=microsoft.jet.oledb.4.0; _
extended properties=excel 8.0;data source=
ThisWorkbook.FullName
Sheet3.Activate
Sql = select a.存货类,a.fh ,b.hk from (select 存货类,sum(本月发货数量) _
as fh from [入库$] where 存货类 is not null and 区域= [b2] _
and month(日期)= [d2] group by 存货类) as a _
left join (select 存货类,sum(数量) as hk from [回款$] where 存货类
_
is not null and 区域= [b2] and month(开票日期)=
[d2] _
group by 存货类) as b on a.存货类=b.存货类
Range(a5).CopyFromRecordset conn.Execute(Sql)
End Sub
显示全部