系统:Windows 7
软件:Excel 2010 / Access 2010
这个系列开展一个新的篇章,重点关注Access数据库
主体框架:以Excel作为操作界面,Access作为数据库
今天讲讲,如何从存在重复值的字段中消除重复,同样的信息只保留一个
涉及知识:
ADO
,SQL:Select
从地址表中获取含有的省份信息,结果是:广东省,湖南省,安徽省
那么怎么使用SQL实现呢
地址数据表
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 = Nothing
End Sub
代码截图
执行结果
核心SQL:Select distinct 省份 from 地址
中文释义:
从地址中获取省份字段非重复的值
关键字:distinct,在字段前加上这个关键字,输出值中就没有重复值
核心SQL
联系客服