删除行中的重复单元格

只是为了澄清:我不想删除重复的行,我想删除行内的重复单元格

所以这是一个经典的地址表,在某一行有重复的条目,我需要删除这些条目。 我在VBA中看到的大部分内容都是用来删除列中的重复值,但是我找不到在一行中删除重复值的方法。

Name | Address1 | Address2 | City | Country Peter | 2 foobar street |2 foobar street | Boston | USA 

我想要它是这样的:

 Name | Address1 | Address2 | City | Country Peter | 2 foobar street | | Boston | USA 

我已经写了一个macros,将循环遍历所有的行,然后每行的每一列,但我不知道如何在同一行内的不同单元格内发现重复。

这是下面的代码:

 Sub Removedupe() Dim LastRow As Long Dim LastColumn As Long Dim NextCol As Long LastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row LastColumn = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column For counterRow = 1 To LastRow 'I'm stuck here: how to remove a duplicate values within that row? Next counterRow End Sub 

也许这会解决你的问题:

 Sub RemoveDuplicatesInRow() Dim lastRow As Long Dim lastCol As Long Dim r As Long 'row index Dim c As Long 'column index Dim i As Long With ActiveSheet.UsedRange lastRow = .Row + .Rows.Count - 1 lastCol = .Column + .Columns.Count - 1 End With For r = 1 To lastRow For c = 1 To lastCol For i = c + 1 To lastCol 'change lastCol to c+2 will remove adjacent duplicates only If Cells(r, i) <> "" And Cells(r, i) = Cells(r, c) Then Cells(r, i) = "" End If Next i Next c Next r End Sub 

也许这在你的循环中:

 If Range("A1").Offset(counterRow,1) = Range("A1").Offset(counterRow,2) Then Range("A1").Offset(counterRow,2).Clear End If 

可能最简单的就是用字典。 阅读当前单元格。 如果它已经在字典中,则清空单元格,否则将其添加到字典中。

 Dim dict As New Scripting.Dictionary For counterRow = 1 To LastRow key = // get the current cell value If Not dict.Exists(key) Then dict.Add key, "1" Else // clear current cell End If Next counterRow 

更多关于字典在这里: VBA是否有字典结构?

PS:请注意,我的解决scheme删除所有重复,不只是如果他们在第二和第三列,如你的例子。

在你的情况下,重复是相邻的。 要清除这个特殊情况下单列或单行的重复项:

 Sub qwerty() Dim r As Range, nR As Long Set r = Intersect(Cells(13, 1).EntireRow, ActiveSheet.UsedRange) nR = r.Count For i = nR To 2 Step -1 If r(i) = r(i - 1) Then r(i) = "" End If Next i End Sub 

这个代码是第13行的一个例子