我正在尝试让宏在C列中找到重复的条目,然后创建一个消息框,说明找到重复的值,请仔细检查',这里的代码如下:
Sub findduplicates()
Range("C3").Select
Do While ActiveCell.Value <> ""
vtnaddress = ActiveCell.Address
vtn = ActiveCell.Value
Range("C3").Select
Do Until ActiveCell.Address = vtnaddress
If ActiveCell.Value = vtn Then
MsgBox "Duplicate VTN found, please check again"
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
ActiveCell.Offset(1, 0).Select
Loop
End Sub
我的问题是消息框不断弹出(我必须杀死excel以摆脱msgbox),即使找到的重复值只有1个,是不是因为它在循环中?我只是希望msgbox在宏找到所有重复项后消失...
感谢
答案 0 :(得分:2)
这将在列&#34; C&#34;中找到每个重复的消息。活动表
Option Explicit
Sub FindDuplicates()
Dim cell As Range
With Intersect(ActiveSheet.Columns("C"), ActiveSheet.UsedRange)
For Each cell In .Cells
If WorksheetFunction.CountIf(.Resize(cell.Row - .Rows(1).Row + 1), cell.value) > 1 Then MsgBox "Duplicate '" & cell.value & "' in " & cell.Address
Next cell
End With
End Sub
答案 1 :(得分:0)
基本上,当它找到重复时,您不会偏移活动单元格。你做的直到循环保持一遍又一遍地检查同一个单元格。假设你只需要知道是否有重复,你可以通过添加'exit do'行来修复它,如下所示:
Sub findduplicates()
Range("C3").Select
Do While ActiveCell.Value <> ""
vtnaddress = ActiveCell.Address
vtn = ActiveCell.Value
Range("C3").Select
Do Until ActiveCell.Address = vtnaddress
If ActiveCell.Value = vtn Then
MsgBox "Duplicate VTN found, please check again"
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
ActiveCell.Offset(1, 0).Select
Loop
End Sub
也就是说,您可能还希望在找到副本的位置显示MsgBox ...
答案 2 :(得分:0)
使用标志来确定是否存在任何重复值。如果找到重复值,那么您还必须退出第一个Do While循环。
Sub findduplicates()
Dim flagDuplicate As Boolean
Range("C3").Select
Do While ActiveCell.Value <> ""
If flagDuplicate Then
Exit Do
End If
vtnaddress = ActiveCell.Address
vtn = ActiveCell.Value
Range("C3").Select
Do Until ActiveCell.Address = vtnaddress
If ActiveCell.Value = vtn Then
MsgBox "Duplicate VTN found, please check again"
foundDuplicate = True
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
ActiveCell.Offset(1, 0).Select
Loop
End Sub