查找相同记录
我在ExcelA列与B列输入两列数据,两列数据中有若干数据是相同的.我编个程序,将两列数据中相同的数据查找出来.我想对查找出来的相同数据编个序号,如B列中有三个"北京"和两个"上海"与A列记录相同,即A列中也有"北京"和"上海"的记录.我想在C列添加辅助序号,以便对相同数据进行分类编号,如在C列对两个"北京"添加序号1,对三个"上海"添序号2.查找相同数据程序我已编出如下,但不知如何在程序中对相同数据添加序号.
Dim a As Integer, b As Integer, c As Integer
For a = 1 To 10
For b = 1 To 10
If Cells(a, 1) = Cells(b, 2) Then
Cells(b, 3) = 1'在C列添加辅助记录,以表示两列相同数据
End If
Next
Next
[解决办法]
因为数据量不大,就没有考虑算法开销了,直接遍历重复值
Sub EnumerateSameAB() Dim a As Integer, b As Integer, c As Integer Dim n As Integer Dim fnd As Boolean n = 0 For b = 1 To 10 For a = 1 To 10 If Cells(a, 1) = Cells(b, 2) Then fnd = False For c = 1 To b - 1 If Cells(c, 2) = Cells(b, 2) Then Cells(b, 3) = Cells(c, 3) fnd = True Exit For End If Next If Not fnd Then n = n + 1 Cells(b, 3) = n '在C列添加辅助记录,以表示两列相同数据 End If Exit For End If Next NextEnd Sub
[解决办法]
一个宏搞定。假设A、B两列的字段名称为A、B,文件为E:\Book1.xls。查询结果保存在C1
Sub Macro1()
With ActiveSheet.QueryTables.Add(Connection:=Array( _
"OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Book1.xls;Jet OLEDB:Engine Type=35"), Destination:=Range("C1"))
.CommandType = xlCmdSql
.CommandText = Array("select distinct A from [Sheet1$] where A in (select distinct B from [Sheet1$])")
.Refresh BackgroundQuery:=False
End With
End Sub