VBA Excel remove duplicate values based on values in other column - excel

I have several codes of the same. I can remove duplicates only for these ones, which have the H-column empty. If the H column contains nonempty cell, the given code must stay.
I tried to work with IsEmpty() function, but it didn't work. The behaviour was as normal.
The code looks like this:
If IsEmpty(shTarget.Range("H" & lRow)) Then
With shTarget.Range("A" & lRow)
.PasteSpecial xlPasteValuesAndNumberFormats
.PasteSpecial xlPasteFormats
.RemoveDuplicates Columns:=1, Header:=xlYes
.Sort Key1:=.Columns(1), Order1:=xlAscending, Header:=xlYes
.WrapText = True
End With
End If
The approach with:
If shTarget.Range("H" & lRow) = "" Then
was exactly the same.
How can I retain the duplicate codes, which have value in other column?
UPDATE:
With this approach:
With shTarget.Range("A" & lRow)
.PasteSpecial xlPasteValuesAndNumberFormats
.PasteSpecial xlPasteFormats
If .Range("H" & lRow).Value = "" Then
.RemoveDuplicates Columns:=1, Header:=xlYes
End If
.Sort Key1:=.Columns(1), Order1:=xlAscending, Header:=xlYes
.WrapText = True
End With
I have an error:
Sort method of Range class failed
UPDATE II
Tried also have this one:
For Each r In rng
If r.Value = "" Then
shTarget.Range("A2:H" & lRow).RemoveDuplicates Columns:=1,
Header:=xlYes
End If
Next r
it still doesn't work. Basically, no difference was observed.
My full code is:
Sub CopyData_Cables(ByRef shSource As Worksheet, shTarget As Worksheet)
Const VHead As String = "A1:H1"
Const VMBom As String = "A2:H100"
shSource.Range(VHead).Copy
With shTarget.Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
Dim lRow As Long, lRow2 As Long
Dim i As Integer
lRow = shTarget.Cells(Rows.Count, "A").End(xlUp).Row + 1
shSource.Range(VMBom).Copy
Set Rng = shTarget.Range("H2" & lRow)
If IsEmpty(shTarget.Range("H" & lRow)) Then
With shTarget.Range("A" & lRow)
.PasteSpecial xlPasteValuesAndNumberFormats
.PasteSpecial xlPasteFormats
.RemoveDuplicates Columns:=1, Header:=xlYes
.Sort Key1:=.Columns(1), Order1:=xlAscending, Header:=xlYes
.WrapText = True
End With
End If
'If shTarget.Range("H2" & lRow) <> "" Then
'shTarget.Range("A" & lRow).Value = 0
'End If
'For Each r In Rng
' If r.Value = "" Then
'shTarget.Range("A2:A" & lRow).Value = "Kurs!"
' End If
' Next r
shTarget.Columns("A").ColumnWidth = 6.11
shTarget.Columns("B").ColumnWidth = 50
shTarget.Columns("C").ColumnWidth = 50
shTarget.Columns("D").ColumnWidth = 5.44
shTarget.Columns("E").ColumnWidth = 5.89
shTarget.Columns("F").ColumnWidth = 9
shTarget.Columns("G").ColumnWidth = 21.22
shTarget.Columns("H").ColumnWidth = 10.89
shTarget.Rows.EntireRow.AutoFit
For i = 3 To lRow Step 4
shTarget.Range(shTarget.Cells(i, 1), shTarget.Cells(i, 5)).Interior.Color = RGB(235, 235, 235)
shTarget.Range(shTarget.Cells(i, 7), shTarget.Cells(i, 8)).Interior.Color = RGB(235, 235, 235)
Next i
' Reset the clipboard.
Application.CutCopyMode = xlCopy
End Sub

Scan up the sheet deleting the duplicate rows.
Option Explicit
Sub RemoveDuplicates()
Dim ws As Worksheet, dict
Dim lastrow As Long, i As Long, n As Long
Dim key As String
Dim fso, ts
Set fso = CreateObject("Scripting.FilesystemObject")
Set ts = fso.CreateTextFile("debug.txt")
Set dict = CreateObject("Scripting.Dictionary")
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = lastrow To 2 Step -1
If Len(Trim(.Cells(i, "H"))) = 0 Then
key = Trim(.Cells(i, "A"))
If dict.exists(key) Then
'.Cells(i, "A").Interior.Color = vbRed
.Rows(i).Delete
n = n + 1
Else
dict.Add key, i
End If
Else
key = ""
End If
ts.writeline i & " A='" & .Cells(i, "A") & "' H='" _
& .Cells(i, "H") & "' key='" & key & "' n=" & n
Next
End With
ts.Close
MsgBox n & " rows deleted", vbInformation
End Sub

Related

Userform button not calling code on Module

I have a Userform with the following code attached to the "OK" button. All the code works fine other than the last 4 lines. Full code associated to OK button shown below, code not working is:
Dim SheetName As String
SheetName = ActiveSheet.Name
Call SheetCleanup
Worksheets(SheetName).Activate
It is as if it completely ignores it. SheetCleanup is located in a Module, and my suspicions are that there is an issue going from a Userform to a Module? But I am unfamiliar with this.
Full code is here:
Private Sub CommandButtonOK_Click()
If ComboBoxTargetEvent.Value = "" Or ComboBoxDesigner.Value = "" Or ComboBoxSignoff.Value = "" Or ComboBoxCarArea.Value = "" Or ComboBoxOriginator.Value = "" Or TextBoxNumberOfJobs.Value = "" Or ComboBoxProjectTitle.Value = "" Then _
MsgBox "You must complete all fields", vbInformation
Else:
'Go to worksheet based on Car Area
Dim CarArea As String
CarArea = ComboBoxCarArea.Value
Worksheets(CarArea).Activate
'Enter Target Event Into Column A
Columns("A").Find("", Cells(Rows.Count, "A")).Value = ComboBoxTargetEvent.Value
'Enter Project Title into column B
Columns("A").Find("", Cells(Rows.Count, "A")).Offset(-1, 1).Value = ComboBoxProjectTitle.Value
'Enter Designer name into column E
If _
ComboBoxDesigner.Value <> "Various" Then _
Columns("A").Find("", Cells(Rows.Count, "A")).Offset(-1, 4).Value = ComboBoxDesigner.Value
'Enter Sign-off name into column F
If _
ComboBoxSignoff.Value <> "Various" Then _
Columns("A").Find("", Cells(Rows.Count, "A")).Offset(-1, 5).Value = ComboBoxSignoff.Value
'Enter Originator name into column F
If _
ComboBoxOriginator.Value <> "Various" Then _
Columns("A").Find("", Cells(Rows.Count, "A")).Offset(-1, 3).Value = ComboBoxOriginator.Value
'Enter Data Formula into columns H & I
Columns("A").Find("", Cells(Rows.Count, "A")).Offset(-2, 7).Select
Columns("A").Find("", Cells(Rows.Count, "A")).Offset(-2, 7).Copy
Selection.Offset(1, 0).PasteSpecial Paste:=xlPasteFormulas
Columns("A").Find("", Cells(Rows.Count, "A")).Offset(-2, 8).Select
Columns("A").Find("", Cells(Rows.Count, "A")).Offset(-2, 8).Copy
Selection.Offset(1, 0).PasteSpecial Paste:=xlPasteFormulas
'Enter temp values into C & G
Columns("A").Find("", Cells(Rows.Count, "A")).Offset(-1, 2).Value = "ENTER DESCRIPTION HERE (CAPS LOCK ONLY)"
Columns("A").Find("", Cells(Rows.Count, "A")).Offset(-1, 6).Value = "ENTER DATE"
'Enter "N" into Job Completed
Columns("A").Find("", Cells(Rows.Count, "A")).Offset(-1, 9).Value = "N"
'Enter Data Validation List for Target Event
Dim ws As Worksheet
Dim NumberOfJobs As Long
Dim LastUsedInAA As Long
Dim range9 As Range
Set ws = ThisWorkbook.Worksheets("VBA_Data")
Set range9 = ws.Range("a:a")
LastUsedInAA = Range("A" & Rows.Count).End(xlUp).Row
NumberOfJobs = TextBoxNumberOfJobs.Value
If NumberOfJobs <> 0 Then
Range("A" & LastUsedInAA).Select
Selection.Resize(Selection.Rows.Count + NumberOfJobs - 1, _
Selection.Columns.Count).Select
With Selection.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range9.Address
End With
End If
'Enter Data Validation List for Designer
Dim LastUsedInE As Long
Dim range1 As Range
Set ws = ThisWorkbook.Worksheets("VBA_Data")
Set range1 = ws.Range("c:c")
LastUsedInE = Range("E" & Rows.Count).End(xlUp).Row
NumberOfJobs = TextBoxNumberOfJobs.Value
If NumberOfJobs <> 0 Then
Range("E" & LastUsedInE).Select
Selection.Resize(Selection.Rows.Count + NumberOfJobs - 1, _
Selection.Columns.Count).Select
With Selection.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range1.Address
End With
End If
'Enter Data Validation List for Senior Designer
Dim LastUsedInF As Long
Dim range2 As Range
Set ws = ThisWorkbook.Worksheets("VBA_Data")
Set range2 = ws.Range("b:b")
LastUsedInF = Range("F" & Rows.Count).End(xlUp).Row
NumberOfJobs = TextBoxNumberOfJobs.Value
If NumberOfJobs <> 0 Then
Range("F" & LastUsedInF).Select
Selection.Resize(Selection.Rows.Count + NumberOfJobs - 1, _
Selection.Columns.Count).Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range2.Address
End With
End If
'Enter Data Validation List for Originator
Dim LastUsedInD As Long
Dim range5 As Range
Set ws = ThisWorkbook.Worksheets("VBA_Data")
Set range5 = ws.Range("f:f")
LastUsedInD = Range("D" & Rows.Count).End(xlUp).Row
NumberOfJobs = TextBoxNumberOfJobs.Value
If NumberOfJobs <> 0 Then
Range("d" & LastUsedInD).Select
Selection.Resize(Selection.Rows.Count + NumberOfJobs - 1, _
Selection.Columns.Count).Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range5.Address
End With
End If
'Enter Data Validation List for Job Completed
Dim LastUsedInJ As Long
Dim range3 As Range
Set ws = ThisWorkbook.Worksheets("VBA_Data")
Set range3 = ws.Range("d:d")
LastUsedInJ = Range("J" & Rows.Count).End(xlUp).Row
NumberOfJobs = TextBoxNumberOfJobs.Value
If NumberOfJobs <> 0 Then
Range("J" & LastUsedInJ).Select
Selection.Resize(Selection.Rows.Count + NumberOfJobs - 1, _
Selection.Columns.Count).Select
With Selection.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range3.Address
End With
End If
'Multiply rows for multiple jobs
Dim LastUsedInA As Long
LastUsedInA = Range("A" & Rows.Count).End(xlUp).Row
NumberOfJobs = TextBoxNumberOfJobs.Value
If NumberOfJobs <> 1 Then
Range("A" & LastUsedInA).Select
Selection.Resize(Selection.Rows.Count, _
Selection.Columns.Count + 10).Copy
Range("A" & LastUsedInA + 1).Select
Selection.Resize(Selection.Rows.Count + NumberOfJobs - 2, _
Selection.Columns.Count).Select
Selection.PasteSpecial Paste:=xlPasteValues
Selection.PasteSpecial Paste:=xlPasteFormulas
End If
'Clear the clipboard
Application.CutCopyMode = False
'select last cell in A
Range("A" & LastUsedInA).Select
'Clear all fields before hide
ComboBoxTargetEvent.Value = ""
ComboBoxDesigner.Value = ""
ComboBoxSignoff.Value = ""
ComboBoxCarArea.Value = ""
ComboBoxOriginator.Value = ""
TextBoxNumberOfJobs.Value = ""
ComboBoxProjectTitle.Value = ""
'Hide Window
CreateJobs.Hide
End If
Dim SheetName As String
SheetName = ActiveSheet.Name
Call SheetCleanup
Worksheets(SheetName).Activate
End Sub
Code for SheetCleanup is as follows:
Public Sub SheetCleanup()
'Clan-up on Car Area WorkSheets
Application.ScreenUpdating = False
Dim sh As Worksheet
For Each sh In ActiveWorkbook.Worksheets
Select Case sh.Name
Case Is = "Contents Page", "Completed", "VBA_Data", "Front Team Project List", "Mid Team Project List", "Rear Team Project List", "Acronyms"
Case Else
With sh
'set zoom
sh.Activate
ActiveWindow.Zoom = 100
'format columns and rows
.Columns("g:g").NumberFormat = "dd-mm"
.Columns("i:i").NumberFormat = "0"
.Columns("A").ColumnWidth = 27
.Columns("B").ColumnWidth = 50
.Columns("C").ColumnWidth = 50
.Columns("D").ColumnWidth = 21
.Columns("E").ColumnWidth = 27
.Columns("F").ColumnWidth = 21
.Columns("G").ColumnWidth = 10
.Columns("H").ColumnWidth = 15
.Columns("I").ColumnWidth = 22
.Columns("J").ColumnWidth = 17
.Rows("1").RowHeight = 77.2
.Rows("2").RowHeight = 10
.Rows("3").RowHeight = 30
.Rows("4").RowHeight = 10
.Rows("5").RowHeight = 18
.Columns("a:j").HorizontalAlignment = xlCenter
.Columns("b:c").HorizontalAlignment = xlLeft
.Rows("3").HorizontalAlignment = xlCenter
.Rows("5").HorizontalAlignment = xlCenter
.Range("A:J").Validation.Delete
'set data validation for Target Event
Dim ws As Worksheet
Dim wsVBA As Worksheet
Dim range1 As Range, rng As Range
Dim LastRowTargetEvent As Long
Set wsVBA = ThisWorkbook.Worksheets("VBA_Data")
LastRowTargetEvent = wsVBA.Cells(.Rows.Count, "A").End(xlUp).Row
Set range1 = wsVBA.Range("A2:A" & LastRowTargetEvent)
Set ws = ActiveSheet
Set rng = ws.Range("a6:a1000")
With rng.Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & wsVBA.Name & "'!" & range1.Address
End With
End With
End Select
Next sh
End Sub

subtotal wih conditonally group using VBA

I want to group column name :Check,Code No1,Code 2,Status and total result in Number column according to group using VBA
Data
Result
This is my code:
Sub Sample()
Dim ws As Worksheet, ws1 As Worksheet
Dim LastRowWs As Long, LastRowWs1 As Long, i As Long
Dim Delrange As Range
Application.ScreenUpdating = False
On Error GoTo Whoa
Set ws = Sheets("Sheet1"): Set ws1 = Sheets("Sheet2")
ws1.Cells.Delete
LastRowWs = ws.Range("A" & Rows.Count).End(xlUp).Row
LastRowWs1 = LastRowWs
ws.Range("A1:F" & LastRowWs).Copy ws1.Range("A1")
With ws1
.Columns("A:F").Sort Key1:=.Range("A:F"), Order1:=xlAscending, Key2:=.Range("B2") _
, Order2:=xlAscending, Header:=xlGuess, OrderCustom:=4, MatchCase:= _
True, Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, DataOption2 _
:=xlSortNormal
With .Range("A1:F" & LastRowWs1)
.Subtotal GroupBy:=2, Function:=xlSum, TotalList:=Array(5), Replace:=False, _
PageBreaks:=False, SummaryBelowData:=True
.Subtotal GroupBy:=3, Function:=xlSum, TotalList:=Array(5), Replace:=False, _
PageBreaks:=False, SummaryBelowData:=True
.Subtotal GroupBy:=4, Function:=xlSum, TotalList:=Array(5), Replace:=False, _
PageBreaks:=False, SummaryBelowData:=True
End With
LastRowWs1 = .Range("D" & Rows.Count).End(xlUp).Row
'.Rows(LastRowWs1 + 1 & ":" & Rows.Count).ClearContents
.Range("A1:F" & LastRowWs1).Copy
.Range("A1:F" & LastRowWs1).PasteSpecial xlPasteValues
i = LastRowWs1
Do While i > 1
'If InStr(1, .Range("A" & i).Value, "", vbTextCompare) Then
If InStr(1, .Range("D" & i).Value, "Total", vbTextCompare) Then
i = i - 1
Else
If Delrange Is Nothing Then
Set Delrange = .Rows(i - 1)
Else
Set Delrange = Union(Delrange, .Rows(i))
'i = i - 1
End If
End If
i = i - 1
' End If
Loop
If Not Delrange Is Nothing Then Delrange.Delete: Set Delrange = Nothing
LastRowWs1 = .Range("D" & Rows.Count).End(xlDown).Row
'For i = LastRowWs1 To 2 Step -1
For i = 1 To LastRowWs1
If (InStr(1, .Range("D" & i).Value, "Total", vbTextCompare)) Then
.Range("F" & i - 1).Value = .Range("F" & i).Value
If Delrange Is Nothing Then
Set Delrange = .Rows(i)
Else
Set Delrange = Union(Delrange, .Rows(i))
End If
End If
Next i
If Not Delrange Is Nothing Then Delrange.Delete
.Cells.RemoveSubtotal
End With
MsgBox "Vandana, Please check Sheet 'Output' :-)"
LetsContinue:
Application.ScreenUpdating = True
On Error Resume Next
Set ws = Nothing: Set ws1 = Nothing
On Error GoTo 0
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
But result is like this
●★ 100 101 PG is same column group but sum result is separately
See like this:
Somethings you will need to change in Pivot Visualization:
Tabular Form Data
SubTotals Off
Totals Off
Item repeat for each column
Link to File

Delete data older than a month for every sheet

I have an Excel file with many sheets, and I would like to filter old data at the end of the month and delete it. I can't always clear the data on the first, and sometimes users will work on the workbook before I can set it up for the current month.
This is the code I currently have:
Private Sub CommandButton4_Click()
Dim ws As Worksheet
Dim Rng As Range
Dim LastRow As Long, LastCol As Long
response = MsgBox("Tem a Certeza que quer Limpar todo os Dados?", vbYesNo)
If response = vbNo Then Exit Sub
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Formularios" Then
If ws.Name <> "Coordenador" Then
If ws.Name <> "LookupList" Then
With ws
.Unprotect Password:=pass
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
LastCol = .Range("A" & .Columns.Count).End(xlToLeft).Column
Set Rng = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
End With
With Rng
.AutoFilter Field:=1, Criteria1:=xlFilterLastMonth
.SpecialCells(xlCellTypeVisible).Offset(1, 0).Resize(.Rows.Count).Rows.Delete
End With
With ws
.AutoFilterMode = False
If .FilterMode = True Then
.ShowAllData
End If
.Protect Password:=pass
End With
End If
End If
End If
Next
End Sub
I get an Error 1004 object on this line:
.SpecialCells(xlCellTypeVisible).Offset(1, 0).Resize(.Rows.Count).Rows.Delete
This is the form I typically use.
With ws
.Unprotect Password:=pass
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
LastCol = .cells(1, .Columns.Count).End(xlToLeft).Column
Set Rng = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
End With
With Rng
.AutoFilter Field:=1, Criteria1:=xlFilterLastMonth, Operator:=xlFilterDynamic
with .resize(.rows.count-1, .columns.count).offset(1, 0)
if cbool(application.subtotal(103, .cells)) then
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
end if
end with
End With
I changed the initial range (rng) to be only the second row and took out the offset and resize. Since the range is only used in this subroutine, why is it being resized?
I tested it with 5 or 6 dates in this month and last, even putting them out of order and it worked as expected.
sub stest()
With Worksheets(1)
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
Set Rng = .Range(.Cells(2, 1), .Cells(LastRow, 1))
End With
With Rng
.AutoFilter Field:=1, Criteria1:=xlFilterLastMonth, Operator:=xlFilterDynamic
.offset(1,0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
End Sub

VBA - Loop through rows and delete if multiple values exists

I wish to optimize my code which loops through all rows and deletes it if a certain value exists. However, I am currently looping through > 100000 rows, so I wish to improve the speed.
Main purpose: Loop through all rows and delete it if a) cell(row, "A").value = "X1", b) cell(row, "S").value = "X2", and c) cell(row, "AW").value = "X3".
My current code is as follows:
Call FilterData("A", "X1")
Call FilterData("S", "X2")
Call FilterData("AW", "X3")
Sub FilterData(Column as String, Check as String)
Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
Dim CalcMode As Long
Dim ViewMode As Long
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
End With
If Not Sheets("XXX").AutoFilterMode Then
Sheets("XXX").Range("1:1").AutoFilter
End If
Sheets("XXX").Range("A2:BT1048576").Sort _
Key1:=Sheets("XXX").Range(Column & "1"), Order1:=xlAscending
With Sheets("XXX")
.Select
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
.DisplayPageBreaks = False
Firstrow = .UsedRange.Cells(1).Row
Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
For Lrow = Lastrow To Firstrow Step -1
With .Cells(Lrow, Column)
If Not IsError(.Value) Then
If .Value = Check Then .EntireRow.Delete
End If
End With
Next Lrow
End With
End Sub
Optimizing by applying a autofiler against the columns you wish to delete, if the values exist, the code deletes them. I made this really quickly, untested, but the logic works, hope this helps! :)
Code Added:
Sub Filter()
Dim ColALookup As String
Dim ColSLookup As String
Dim colAWlookup As String
Dim i As Long
ColALookup = "X1"
ColSLookup = "X2"
colAWlookup = "X3"
With Sheets("XXX")
.Range("A2", .Range("A" & .Rows.Count).End(xlUp)) _
.AutoFilter Field:=1, Criteria1:=Application.Transpose(ColALookup), Operator:=xlFilterValues
.Range("S2", .Range("S" & .Rows.Count).End(xlUp)) _
.AutoFilter Field:=1, Criteria1:=Application.Transpose(ColSLookup), Operator:=xlFilterValues
.Range("AW2", .Range("AW" & .Rows.Count).End(xlUp)) _
.AutoFilter Field:=1, Criteria1:=Application.Transpose(colAWlookup), Operator:=xlFilterValues
.Range("A2", .Range("A" & .Rows.Count).End(xlUp)) _
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
.Range("S2", .Range("S" & .Rows.Count).End(xlUp)) _
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
.Range("AW2", .Range("AW" & .Rows.Count).End(xlUp)) _
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
.AutoFilterMode = False
End With
End Sub

Find duplicates within five columns

I have dataset from columns A to K and would like find duplicate rows of data from columns A, D, F, J and K.
I have the following code:
Sub RemoveDupes2()
Dim r As Long, lr As Long
Application.ScreenUpdating = False
lr = Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
With Range("L2:L" & lr)
.Formula = "=ROW()"
.Value = .Value
End With
Range("A2:L" & lr).Sort Key1:=Range("A2"), Order1:=1, Key2:=Range("B2"), Order2:=1
With Range("M2:M" & lr)
.FormulaR1C1 = "=RC[-12]&RC[-11]&RC[-6]&RC[-4]&RC[-2]"
.Value = .Value
End With
With Range("N2:N" & lr)
.FormulaR1C1 = "=COUNTIF(R1C13:RC[-1],RC[-1])"
.Value = .Value
End With
For r = lr To 2 Step -1
If Cells(r, 14).Value > 2 Then
Rows(r).Delete
ElseIf Cells(r, 14).Value = 2 Then
Cells(r - 1, 1).Resize(, 7).Font.Bold = True
Rows(r).Delete
End If
Next r
lr = Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
Range("A2:L" & lr).Sort Key1:=Range("L2"), Order1:=1
Range("L2:N" & lr).ClearContents
Application.ScreenUpdating = True
End Sub
The code currently deletes the entire data set and I am not sure why its doing so, as I am novice user to VBA.
https://www.dropbox.com/s/otgkk1igcd2995t/duplicates.xlsx
In your first With, please try changing:
.FormulaR1C1 = "=RC[-12]&RC[-11]&RC[-6]&RC[-4]&RC[-2]"
to
.FormulaR1C1 = "=RC[-12]&RC[-9]&RC[-7]&RC[-3]&RC[-2]"
There may well however be a separate issue because even unaltered the above code does not delete the entire dataset (for me, with Excel 2007).

Resources