2013-07-16 41 views
0

我正在尝试完成一个小数据清理任务,并且希望使用Excel VBA而不是我通常的Python。VBA处理连续单元格中的重复

我有列在每一行上的项目列表。不幸的是,这些列表中有重复的项目需要删除。可以假设每个列表最多只有15个项目。

我在伪代码尝试

Foreach row in selection: 
Check Column n and n+1. (so thats column A and B for the first iteration) 
If different, n++ 
If the same, remove the cell N+1 and shift all values to the right right of N+1 left 1 cell. 
Check (n, n+1) again after. 

我重视的几个例子行。任何帮助将不胜感激 - 不幸的是,我发现VBA比我迄今为止解决的任何其他语言都难。

下面的所有三行应该减少到相同的东西。

1苹果香蕉巧克力狗
2苹果香蕉巧克力巧克力巧克力狗
3苹果香蕉巧克力巧克力巧克力巧克力巧克力犬犬犬犬

这三个例子都应该减少到

苹果香蕉巧克力狗

+0

很公平,甚至** ** VBA可以做这样的一个递归,如果这就是你要求的... :) – AKDADEVIL

+0

它可以递归地做它?! – Pythonn00b

回答

2

当然可以,

将一个Commandbutton som ewhere您的Excel工作表,并把这个代码在VBA编辑:

Private Sub CommandButton1_Click() 
    RecurseRows 'Start recursion 
End Sub 

Private Sub RecurseRows(Optional row As Long = 1) 
    RecurseColumns row, 1, 2 

    If (row = ActiveSheet.Range("A65536").End(xlUp).row) Then 
     Exit Sub 'End recursion when next row is empty 
    Else 
     RecurseRows row + 1 'next row 
    End If 
End Sub 

Private Sub RecurseColumns(row As Long, col1 As Long, col2 As Long) 
    If (IsEmpty(ActiveSheet.Cells(row, col2))) Then 
     Exit Sub 'End recursion 
    Else 
     If (ActiveSheet.Cells(row, col1) = ActiveSheet.Cells(row, col2)) Then 
      ActiveSheet.Cells(row, col2).Delete xlShiftToLeft 'Remove duplicate 
      RecurseColumns row, col1, col2 'Check same couple again, since col2 has changed 
     Else 
      RecurseColumns row, col2, col2 + 1 'Shift one cell to the right 
     End If 
    End If 
End Sub 

当然,你可以做到这一点反复,太... XD

+0

我正在尝试做迭代!我不知道在VBA中可以进行递归。看起来有很多东西需要学习。非常感谢你做的这些 – Pythonn00b