ADO+EXCEL通用程序样版。
Sub ADORecordset()
Dim Sql$
Dim RST As New ADODB.Recordset '若要使用 RST.RecordCount 计算记录个数,此项必须,故一定要设置引用:
'VBE 中菜单“工具-引用-Microsoft ActiveX Data Objects 2.0 Library”
'(1)定义对象
Set Conn = CreateObject("adodb.connection") '(2)设置 connection 对象
Set RST = CreateObject("Adodb.Recordset") '(3)设置 Recordset 对象
Conn.Open "provider=microsoft.jet.oledb.4.0;extended properties=excel 8.0;data source=" & ThisWorkbook.FullName
'(4)打开连接
Sql = "Select * from [Sheet1$] where 字段='020009' or 字段='050023' or 字段='010024'"
'(5)设置 Sql 语句
RST.Open Sql, Conn, adOpenStatic 'adOpenStatic静态指针,以便计算记录个数
'(6)执行 Sql 语句
MsgBox "找到" & RST.RecordCount & "个记录" '(7)可使用 RST.RecordCount 得到记录个数
Sheets(2).Range("a2").CopyFromRecordset RST '(8)结果放置
Sheets(2).Activate
RST.Close: Conn.Close '(9)关闭连接
Set RST = Nothing: Set Conn = Nothing '(10)对象置空
End Sub
'使用 ADO-SQL 处理 EXCEL 文件的程序架构一
Sub ADOConn()
Dim Sql$
Set Conn = CreateObject("adodb.connection")
Conn.Open "provider=microsoft.jet.oledb.4.0;extended properties=excel 8.0;data source=" & ThisWorkbook.FullName
'Sql = "select * from [Sheet1$] where Part NO#='020009' or Part NO#='050023' or Part NO#='010024'"
'Sql = "select PartNO from [Sheet1$] where PartNO='020009'"
Sql = "Select * from [Sheet1$] where 字段='020009' or 字段='050023' or 字段='010024'"
Sheets(2).Range("a2").CopyFromRecordset Conn.Execute(Sql)
Sheets(2).Activate
Conn.Close
Set Conn = Nothing
End Sub