Access/VBA/Excel-12-模糊查询


Part 1:目标

商品清单
图片

  1. 根据商品ID检索需要的商品

  2. 通过模糊检索实现,有点百度的味道,只知道部分信息,来查询

  3. 逻辑过程

    • 连接数据库
    • 根据需求确定***SQL***语句
    • 执行SQL*语句,得到recordset*
    • 将***recordset***写入工作表(字段名+所有记录 列名+每一行)
    • 断开与数据库的连接
  4. 检索商品ID首字母为m的商品

Part 2:代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Sub test()        
Dim cnn As New ADODB.Connection '连接
Dim rs As New ADODB.Recordset
Dim SQL As String
Dim tblName
Dim dbAddr

dbAddr = ThisWorkbook.Path & "\商品清单.accdb"
tblName = "商品清单"

'连接数据库
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open "Data Source=" & dbAddr
End With

opFilds = "商品ID,商品名称,厂家,数量"
searchC = "商品ID like 'm%'"

SQL = "Select " & opFilds & " from " & tblName & " where (" & searchC & ")"
Set rs = cnn.Execute(SQL)
Dim sht
Dim fildNum
Set sht = ThisWorkbook.Worksheets("示例")
sht.Cells.ClearContents

fildNum = rs.Fields.Count
For j = 0 To fildNum - 1 Step 1
fildName = rs.Fields(j).Name
sht.Cells(1, j + 1) = fildName
Next j

sht.Cells(2, 1).CopyFromRecordset rs

cnn.Close
Set rs = Nothing
Set cnn = NothingEnd Sub

代码截图
图片

执行结果
图片

Part 3:部分代码解读

  1. Select 商品ID,商品名称,厂家,数量 from 商品清单 where (商品ID like 'm%')
  2. 中文释义:选取满足商品ID第1位为字母*m*的商品信息,从结果看,没有区分大小写
  3. 这样的***%表示0*或者任意字符,有点像*的作用

Part 4:延伸


  • _代表单一字符,searchC = "商品ID like '____'"四个下划线,结果如下

图片

  • []指定范围,searchC = "商品ID like '[0-9]%'",表示***0-9***开头的字符串,结果如下

图片

  • [ ]指定范围,searchC = "商品ID like '[a-z]%'",表示a-z开头的字符串,依然没有区分大小写,结果如下

图片

  • [!]指定范围之外,searchC = "商品ID like '[!a-z]%'",表示不以***a-z***开头,结果如下

    图片

  • not like取反,searchC = "商品ID not like '[a-z]%'",表示不满足a-z开头的字符串,依然没有区分大小写,结果如下

图片