2016-07-29 82 views
0

我目前正在运行一个宏,它标识工作簿中的重复项,但它标识第一个设置了索引并且不标记第一个设置,然后导致我设置一个if语句通过这个,这也增加了一审副本。然而这需要很长时间,如果可能的话,我们希望改善这一点。任何建议将不胜感激,我是VBA的新手,但一直在学习,因为我遇到了新问题!VBA - IF循环改进

'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 
+0

迭代Range.Value数组而不是使用单独的Range/Cell应该会有所帮助。你也可以用公式'= IF(MATCH($ A2,$ A:$ A,0)<> ROW($ A2),“Duplicate”,“”)'得到相同的结果。 –

回答

0

我的第一个建议是没有的事情过度复杂化,尝试使用重复值的条件格式,看是否能帮助:

enter image description here

如果做不到这一点,如果你是急于找到只重复,而不是第一次出现,您可以使用像这样的公式:(在单元格B2中,如果您的数据以A2开头,则需要不匹配的标题行,或者您的第一行将始终匹配)

=IF(COUNTIF($A1:A$1,A2)>=1,"Duplicate","") 

,当粘贴了你的数据的行可能是这个样子:

enter image description here

也有VBA的解决方案,如果你是绝望的VBA解决方案,但我想我给你简单首先。让我知道你在评论中的表现。

编辑:你可以插入使用VBA上述公式,以R1C1表示法,例如:

Sub test() 
    Range("B2:B" & Range("A1").End(xlDown).Row).FormulaR1C1 = "=IF(COUNTIF(R1C1:R[-1]C1,RC1)>=1,""Duplicate"","""")" 
End Sub 

我会打破这个,所以你知道发生了什么。

Range("B2:B" & Range("A1").End(xlDown).Row)选择B2和A列中的最后一排装满即Range("A1").End(xlDown).Row(所以如果你希望在列A空白为您的数据的一部分,这是不行的)之间的B列的单元

然后,将R1C1参考公式设置为"=IF(COUNTIF(R1C1:R[-1]C1,RC1)>=1,""Duplicate"","""")",其中R1C1表示第一行第一列(即$A$1R[-1]C1表示前一行第一列。例如, 如果您在B5中,则会选择A4。 如果你在A2中,这将选择A1。 如果您在A1中,则会出错,因为您不能在1行之前。 而RC1表示当前行,第一列。

希望这会有所帮助!

+0

嗨安德鲁,我渴望找到所有重复,但它需要用“重复”标记标记它们,因为我进一步处理,以查看重复项所在的类别。这需要是vba解决方案,因为我赢了实际上,我们将会继续前进,其他人不会知道如何找到重复。感谢您对excel的建议,尽管如此! Ged – Hinchy16

+0

对不起,请看我的编辑。 –

+0

再次安德鲁,我只是尝试了你的建议,虽然countif确实需要很长时间,但我认为它比我之前做的循环更好。我最初设计的循环,因为没有任何东西似乎标记所有重复,这是我需要的。我沿着这条线进一步使用它来查找哪些项目列表彼此重叠。感谢您的建议! – Hinchy16

0

答案与我提供的初始代码相同,30000个物品需要大约5分钟的时间,所以它的功能并不算太差。