1.添加ADO接口
工具→引用→找到Microsoft ActiveX Data Objects→确定
2.连接ADO
Dim conn As New ADODB.Connection
conn.Open “Provider = Microsoft.ACE.OLEDB.12.0;Data Source=D:\data\Edata.xlsx;extended properties=”“excel 12.0;HDR=YES”""
conn.Close
3.和sql语句搭配使用
代码:
Sub test()
Dim conn As New ADODB.Connection
conn.Open “Provider = Microsoft.ACE.OLEDB.12.0;Data Source=D:\data\Edata.xlsx;extended properties=”“excel 12.0;HDR=YES”""
'Range(“a1”).CopyFromRecordset conn.Execute(“select * from [data ] u n i o n a l l s e l e c t ∗ f r o m [ d a t a 2 ] union all select * from [data2 ]unionallselect∗from[data2]”)
'Range(“e1”).CopyFromRecordset conn.Execute(“select 姓名,年龄 from[data ] u n i o n a l l s e l e c t 姓 名 , 年 龄 f r o m [ d a t a 2 ] union all select 姓名,年龄 from[data2 ]unionallselect姓名,年龄from[data2]”)
Range(“h1”).CopyFromRecordset conn.Execute(“select * from [data ] w h e r e 性 别 = ′ 男 ′ u n i o n a l l s e l e c t ∗ f r o m [ d a t a 2 ] where 性别='男'union all select * from [data2 ]where性别=′男′unionallselect∗from[data2] where 性别=‘男’”)
conn.Close
End Sub
Sub test()
Dim conn As New ADODB.Connection
Dim sql As String
conn.Open “Provider = Microsoft.ACE.OLEDB.12.0;Data Source=D:\data\Edata.xlsx;extended properties=”“excel 12.0;HDR=YES”""
'Range(“a1”).CopyFromRecordset conn.Execute(“select * from [data ] u n i o n a l l s e l e c t ∗ f r o m [ d a t a 2 ] union all select * from [data2 ]unionallselect∗from[data2]”)
'Range(“e1”).CopyFromRecordset conn.Execute(“select 姓名,年龄 from[data ] u n i o n a l l s e l e c t 姓 名 , 年 龄 f r o m [ d a t a 2 ] union all select 姓名,年龄 from[data2 ]unionallselect姓名,年龄from[data2]”)
'Range(“h1”).CopyFromRecordset conn.Execute(“select * from [data ] w h e r e 性 别 = ′ 男 ′ u n i o n a l l s e l e c t ∗ f r o m [ d a t a 2 ] where 性别='男'union all select * from [data2 ]where性别=′男′unionallselect∗from[data2] where 性别=‘男’”)
'sql = “insert into [data ] ( 姓 名 , 性 别 , 年 龄 ) v a l u e s ( ′ A A ′ , ′ 男 ′ , 33 ) " ′ s q l = " u p d a t e [ d a t a ] (姓名,性别,年龄) values ('AA','男',33)" 'sql = "update [data ](姓名,性别,年龄)values(′AA′,′男′,33)"′sql="update[data] set 性别=‘男’,年龄=1 where 姓名=‘张三’”
'sql = “select [data ] . 姓 名 , 性 别 , 年 龄 , 月 薪 f r o m [ d a t a ].姓名,性别,年龄,月薪 from [data ].姓名,性别,年龄,月薪from[data] left join [data3 ] o n [ d a t a ] on [data ]on[data].姓名=[data3 ] . 姓 名 " s q l = " s e l e c t a . 姓 名 , 性 别 , 年 龄 , 月 薪 f r o m ( s e l e c t ∗ f r o m [ d a t a ].姓名 " sql = "select a.姓名,性别,年龄,月薪 from (select * from [data ].姓名"sql="selecta.姓名,性别,年龄,月薪from(select∗from[data] union all select * from [data2 ] ) a l e f t j o i n [ d a t a 3 ])a left join [data3 ])aleftjoin[data3] on a.姓名 = [data3$].姓名”
Range(“a2”).CopyFromRecordset conn.Execute(sql)
conn.Close
End Sub