2014-03-13 33 views
2

我目前有一個VBA宏,它已經做到了,但並不完全是我所需要的。查找並刪除行中的重複單元格,而不是列

這裏的VBA:

Sub StripRowDupes() 
    Do Until ActiveCell = "" 
     Range(ActiveCell, ActiveCell.End(xlToRight)).Select 
     For Each Cell In Selection 
      If WorksheetFunction.CountIf(Selection, Cell) > 1 Then 
       Cell.ClearContents 
      Else 
      End If 
     Next Cell 
     On Error Resume Next 
     Selection.SpecialCells(xlCellTypeBlanks).Delete Shift:=xlToLeft 
     ActiveCell.Range("A2").Select 
    Loop 
End Sub 

和示例片數據(是在每行中重複):

A | B | C | D 
dog | cat | goat | dog 
car | ship | plane | ship 

運行此宏之後,它刪除第一行和結果副本的實例如下所示:

A | B  | C 
cat | goat | dog 
car | plane | ship 

我需要的是刪除重複的最後一個實例,不是第一,有以下結果:

A | B | C 
dog | cat | goat 
car | ship | plane 

什麼在當前VBA腳本改爲得到期望的結果?

回答

3

UPD:

Sub StripRowDupes() 
    Dim c As Range, rng As Range 
    Dim lastcol As Long 
    Dim i As Long 
    Dim rngToDel As Range, temp As Range 

    Application.ScreenUpdating = False 

    Set c = ActiveCell 

    Do Until c = "" 
     lastcol = Cells(c.Row, Columns.Count).End(xlToLeft).Column 
     Set rng = c.Resize(, lastcol - c.Column + 1) 

     For i = lastcol To c.Column Step -1 
      If WorksheetFunction.CountIf(rng, c.Offset(, i - 1)) > 1 Then c.Offset(, i - 1).ClearContents 
     Next i 

     On Error Resume Next 
     Set temp = rng.SpecialCells(xlCellTypeBlanks) 
     On Error GoTo 0 

     If Not temp Is Nothing Then 
      If rngToDel Is Nothing Then 
       Set rngToDel = temp 
      Else 
       Set rngToDel = Union(rngToDel, temp) 
      End If 
     End If 

     Set c = c.Offset(1) 
     Set temp = Nothing 
    Loop 

    If Not rngToDel Is Nothing Then rngToDel.Delete Shift:=xlToLeft 

    Application.ScreenUpdating = True 
End Sub 
+1

呀。對於每個人都會很方便......但不幸的是,每個人都無法做到「向後」。 :D – Taosique

+1

@simoco謝謝你似乎以我需要的方式工作 – CamSpy

+0

@simoco似乎陷入了數千行大單。任何解決方法,所以它可以簡單地完成任務,即使它需要更多的時間? – CamSpy

相關問題