【发布时间】:2016-07-29 14:59:15
【问题描述】:
我目前正在运行一个宏,它标识工作簿中的重复项,但是它标识了索引中的第一个集合并且没有标记第一个集合,这导致我设置了一个 if 语句来绕过这个,这也将重复添加到第一个实例。然而,这需要很长时间才能完成,如果可能的话,我们希望对此进行改进。任何建议都将不胜感激,我是 VBA 新手,但在遇到新问题时一直在学习!
'Declaring the lastRow variable as Long to store the last row value in the Column1
Dim lastRow As Long
'matchFoundIndex is to store the match index values of the given value
Dim matchFoundIndex As Long
'iCntr is to loop through all the records in the column 1 using For loop
Dim iCntr As Long
Dim first_dup As Long
Dim tagging As Long
Dim item_code As String
'Finding the last row in the Column 1
lastRow = Range("B1000000").End(xlUp).Row
'
'looping through the column1
For iCntr = 2 To lastRow
'checking if the cell is having any item, skipping if it is blank.
If Cells(iCntr, 1) <> "" Then
'getting match index number for the value of the cell
matchFoundIndex = WorksheetFunction.Match(Cells(iCntr, 1), Range("A1:A" & lastRow), 0)
'if the match index is not equals to current row number, then it is a duplicate value
If iCntr <> matchFoundIndex Then
'Printing the label in the column B
Cells(iCntr, 4) = "Duplicate"
End If
End If
Next
For first_dup = 2 To lastRow
If Cells(first_dup, 5) = "Duplicate" Then
item_code = Cells(first_dup, 1)
For tagging = 2 To lastRow
If Cells(tagging, 1) = item_code Then
Cells(tagging, 5) = "Duplicate"
End If
Next
End If
Next
Example data:
item code
1
2
3
4
1 duplicate
2 duplicate
3 duplicate
4 duplicate
1 duplicate
2 duplicate
3 duplicate
4 duplicate
【问题讨论】:
-
迭代 Range.Value 数组而不是使用单个 Range/Cell 应该会有所帮助。您也可以使用公式
=IF(MATCH($A2,$A:$A,0)<>ROW($A2), "Duplicate", "")获得相同的结果。
标签: vba loops if-statement