VBA使⽤SQL语句检索Excel数据
把Excel当做数据库,⽤ActiveX Data Objects打开连接并使⽤Select语句来查询数据,效率要⽐Workbook.Open和Range().Value效率⾼的多。
下⾯来看以个例⼦:
Sub ExeSQL()
' 引⽤Microsoft ActiveX Data Objects 2.5
' 引⽤Microsoft Scripting Runtime
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim fs As New FileSystemObject
Dim extenName$, connStr$, sqlStr$
extenName = fs.GetExtensionName(ThisWorkbook.FullName) ' ⽂件扩展名
If extenName = "xls" Then '03
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;" & _
"Data Source=" & ThisWorkbook.FullName
ElseIf extenName = "xlsx" Then '07
connStr="Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;" & _
"Data Source=" & ThisWorkbook.FullName
End If
excel连接sql数据库教程Set fs = Nothing
sqlStr = "select x.来源,x.访问次数,x.订单总数,y.成功交易量,y.销售额" & _
" from [订单表$] as x inner join [收⼊表$] as y" & _
" on x.来源=y.来源"
conn.Open connStr
Set rs = conn.Execute(sqlStr)
Sheets("新表").Range("A2").CopyFromRecordset rs
' Sheets("新表").Range("A2").CopyFromRecordset conn.Open(connStr)
Set rs = Nothing: conn.Close: Set conn = Nothing
End Sub
说明:
1、数据库的ConnectionString(连接字符串)的获取,我推荐⼀个⽹址:tionstring/;
2、ConnectionString⾥的DataSource(数据源)是ThisWorkbook.FullName(本⼯作薄);
3、Excel作为数据源时,默认⼯作表的第⼀⾏为字段;
3、本⼯作薄⾥⾯有“订单表”、“收⼊表”和“新表”三个表,第⼀⾏(字段)分别为[来源],[访问次数],[...]等。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论