下面我们来学习一个实例,如何统计出Excel重复的值,并且,将重复的值的后列,添加到头一个重复值的列中!
如下图,C列是VIN码,在此表中,存在多个重复的数据,现在,我们来查找一下,存在重复值的第一个值,在其后面,即右边的列中,显示VIN码对应的行驶里程。
首先,如下图一样,在Excel中添加一个按钮控件,最后,给按钮设置VBA代码,即可完成!
如上图,当点击“开始找”按钮时,就将存在重复的VIN码的第一个值,在其后面的列中,分别显示行驶的里程。
为方便大家学习,下面,贴出VBA源代码:
①通用代码
Dim MyBoot As Integer
Dim MyBoots As Integer
Dim Cfz As Integer
②按钮的代码
MyBoot = 0
ReDim iArray(0)
For i = 2 To 1521
Cfz = 0
If (Application.WorksheetFunction.CountIf(Sheets(2).Range("C2:C1521"), Worksheets(2).Cells(i, 3)) > 1) Then
For j = 0 To UBound(iArray)
If (Worksheets(2).Cells(i, 3).Value = iArray(j)) Then
Cfz = Cfz + 1
End If
Next
If (Cfz > 0) Then
Else
MyBoot = MyBoot + 1
ReDim Preserve iArray(0 + MyBoot)
iArray(0 + MyBoot) = Worksheets(2).Cells(i, 3).Value
End If
End If
Next
Dim h As Integer
For k = 0 To UBound(iArray)
Worksheets(2).Cells(k + 2, 6).Value = iArray(k)
MyBoots = 0
ReDim iArrays(0)
h = 0
For m = 2 To 1521
If (iArray(k) = Worksheets(2).Cells(m, 3)) Then
MyBoots = MyBoots + 1
ReDim Preserve iArrays(0 + MyBoots)
iArrays(0 + MyBoots) = Worksheets(2).Cells(m, 4).Value
End If
Next
For mm = 0 To UBound(iArrays)
h = h + 1
Worksheets(2).Cells(k + 2, h + 6).Value = iArrays(mm)
Next
Next
③代码说明
其中,1521代表该表中的行数。