Access/VBA/Excel-14-消除重复值


Part 1:题目

  1. 从地址表中获取含有的省份信息,结果是:广东省,湖南省,安徽省
  2. 那么怎么使用SQL实现呢

地址数据表
图片

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 = "省份"

SQL = "Select distinct " & opFilds & " from " & tblName

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. **核心*SQL***:Select distinct 省份 from 地址

  2. 中文释义:

    • 地址中获取省份字段非重复的值
    • 关键字:distinct,在字段前加上这个关键字,输出值中就没有重复值

核心SQL
图片