Delete all duplicate rows Excel vba - excel

I have a worksheet with two columns: Date and Name. I want to delete all rows that are exact duplicates, leaving only unique values.
Here is my code (which doesn't work):
Sub DeleteRows()
Dim rng As Range
Dim counter As Long, numRows As Long
With ActiveSheet
Set rng = ActiveSheet.Range("A1:B" & LastRowB)
End With
numRows = rng.Rows.Count
For counter = numRows To 1 Step -1
If rng.Cells(counter) Like rng.Cells(counter) - 1 Then
rng.Cells(counter).EntireRow.Delete
End If
Next
End Sub
It's "Like rng.Cells(counter)-1" that seems to be the cause- I get "Type Mismatch".

There's a RemoveDuplicates method that you could use:
Sub DeleteRows()
With ActiveSheet
Set Rng = Range("A1", Range("B1").End(xlDown))
Rng.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
End With
End Sub

The duplicate values in any column can be deleted with a simple for loop.
Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub

Related

How to sort column2 only but separated by Space and Remove Duplicates

Thus anyone have idea on how to resolved this,
I have many Data to Sort, I want to Sort only Column 2 but separated by Space and also I want to delete duplicate values,
Is there any formula to fix this?
Please see Picture Below
I found this Answer on Google, And it Helps me to fix the Problem
Sub SortAndRemoveDuplicates()
Dim Rng As Range
Dim RngArea As Range
Dim sortRng As Range
Dim lr As Long
Dim i As Long
Dim startRow As Long
If Selection.Columns.Count > 1 Or Selection.Column <> 2 Then
MsgBox "Please select data in column B only and then try again...", vbExclamation
Exit Sub
End If
On Error Resume Next
Set Rng = Selection.SpecialCells(xlCellTypeConstants, 1)
On Error GoTo 0
If Rng Is Nothing Then Exit Sub
Application.ScreenUpdating = False
startRow = Selection.Cells(1).Row
lr = startRow + Selection.Rows.Count - 1
For Each RngArea In Rng.Areas
Set sortRng = RngArea.Resize(, 2)
sortRng.Sort key1:=sortRng.Cells(1), order1:=xlAscending, Header:=xlNo
Next RngArea
For i = lr To startRow Step -1
If Cells(i, 2) = Cells(i - 1, 2) Then
Rows(i).Delete
End If
Next i
Application.ScreenUpdating = True
End Sub

Excel VBA, Check values from columns between sheets and delete duplicate

I need some help with comparing values from one column to another and delating it.
so far I have this:
Sub DelateDuplicates()
delArray = Sheets("Save").Range("B1:B") ' saved values
toDelate = Sheets("Validation").Range("B2:B").Value ' values to be checked and delated
lastRow = toDelate.Range("B1000").End(xlUp).Row ' last row
Firstrow = toDelate.Range("B2").End(xlDown).Row ' First row
Dim i As Long
For Lrow = lastRow To Firstrow Step -1
With Worksheets("Validation").Cells(Lrow, "A")
For i = 0 To UBound(delArray) ' arrays are indexed from zero
If Not IsError(.Value) Then
If .Value = delArray(i) Then
.EntireRow.Delete
Exit For
End If
End If
Next
End With
Next Lrow
End Sub
And I do have an error.
"1004 "Application-defined or Object-defined error" "
I have spent 2 days trying to figure it out so far no luck.
Any help will be appreciated.
I modified your code little bit. You can define your first rows and last row the want you want, I have kept it simple for the sake of concept
Option Explicit
Sub DelateDuplicates()
Dim Lrow As Long
Dim delarray()
With Worksheets("Save")
delarray = .Range("B1:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Value
End With
Dim i As Long
Dim lastrow As Long
Dim firstrow As Long
firstrow = 1
With Worksheets("Validation")
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For Lrow = lastrow To firstrow Step -1
For i = 1 To UBound(delarray)
If Not IsError(.Cells(Lrow, "A").Value) Then
If .Cells(Lrow, "A").Value = delarray(i, 1) Then
.Cells(Lrow, "A").EntireRow.Delete
Exit For
End If
End If
Next i
Next Lrow
End With
End Sub
You can avoid loops within loops by using a Dictionary Object
Option Explicit
Sub DeleteDuplicates()
Dim wsSave As Worksheet, wsValid As Worksheet
Dim iLastRow As Long, iFirstRow As Long, i As Long, n As Long
Dim dict As Object, key, cell As Range
With ThisWorkbook
Set wsSave = .Sheets("Save")
Set wsValid = Sheets("Validation")
End With
Set dict = CreateObject("Scripting.Dictionary")
' get values to delete from Column B
For Each cell In wsSave.Range("B1", wsSave.Cells(Rows.Count, "B").End(xlUp))
key = Trim(cell)
If Len(key) > 0 Then
dict(key) = cell.Row
End If
Next
' scan Validation sheet and delete matching from Save
With wsValid
iFirstRow = .Cells(2, "B").End(xlDown).Row
iLastRow = .Cells(Rows.Count, "B").End(xlUp).Row
For i = iLastRow To iFirstRow Step -1
key = .Cells(i, "A")
If dict.exists(key) Then
.Rows(i).Delete
n = n + 1
End If
Next
End With
' resutl
MsgBox n & " rows deleted between row " & _
iFirstRow & " and " & iLastRow, vbInformation
End Sub

How to delete Excel rows containing cells with less than specific amount of characters in them?

This is what i want to do:
And I tried anwsers in this thread too ;-How do I delete a cell from Excel which contains less than 3 characters? I have only one column in sheet
But I can't get it to work.
I tried some codes like these after searching for a few hours but none of them worked or maybe I am not doing it correctly:
Code 1:
With ActiveSheet
lastrow = .Cells(.Rows.Count, "N").End(xlUp).Row
For i = lastrow To 2 Step -1
If Len(.Cells(i, "N").Value) < 6 Then
.Rows(i).Delete
End If
Next i
Code 2:
Sub M_snb()
[N1:N100] = [if(len(N1:N100)<6,"",N1:N100))]
Columns(14).SpecialCells(4).EntireRow.Delete
End Sub
Deleting rows from Excel is rather "expensive" task, thus it should be not done row-by-row, but all at once for saving time:
Sub RemoveRows()
Dim rowsToDelete As Range
Dim cnt As Long
Dim currentlastRow As Long
Dim ws As Worksheet
Dim myCell As Range
Set ws = Worksheets(1)
currentlastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For cnt = 1 To currentlastRow
Set myCell = ws.Cells(cnt, 1)
If Len(myCell.Value2) < 6 Then
If rowsToDelete Is Nothing Then
Set rowsToDelete = myCell.EntireRow
Else
Set rowsToDelete = Union(rowsToDelete, myCell.EntireRow)
End If
End If
Next cnt
If Not rowsToDelete Is Nothing Then
rowsToDelete.Delete
End If
End Sub
Thus, in the code above, the rowsToDelete is the range with the cells, which are to be deleted. The deletion is carried out only once:
If Not rowsToDelete Is Nothing Then
rowsToDelete.Delete
End If
This code will delete your rows in Column A:
Sub remove_rows()
With ActiveSheet
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = LastRow To 2 Step -1
If Len(Trim(.Range("A" & i).Value)) < 6 Then
.Rows(i).EntireRow.Delete
End If
Next i
End With
End Sub
Change A to any other column if you want.

Delete column based on row value

I have a sheet containing data. I want to delete the columns based on row value.
My code doesn't stop and when I hit escape, it has deleted all of the column from my starting columns.
I want to check values in row 2 from column D to the last used column (I have about 100 columns now) that if they contain C15, C17 and so on then don't do anything, else, delete the columns.
I only have 40k rows. My range, column and row will expand every week so I want to use VBA to cut down formatting time.
Sub test()
'start
Dim LR1 As Long
Dim i As Long
Set ws = ThisWorkbook.ActiveSheet
With ws
LR1 = .Cells(2, .Columns.Count).End(xlToLeft).Column
Dim arr As Variant
Dim x
arr = Array("C15", "C17", "C19", "C20", "C21", "C22", "C23", "C24", "C25", "C28", "C29", "C30", "C32")
For x = LBound(arr) To UBound(arr)
For i = LR1 To 4 Step -1
If .Cells(2, i).Value = arr(x) Then
Else
.Columns(i).Delete
End If
Next i
Next x
End With
End Sub
Besides all the points made in the comments, the main issue is that your looping logic is off. Your outer loop should be the columns, and the inner loop should be the array. But with Select Case this can be simplified this to just one loop anyway.
Perhaps something like this:
Option Explicit
Sub Test()
Dim ws As Worksheet
Set ws = ThisWorkbook.ActiveSheet
With ws
Dim lastCol As Long, i As Long
Dim rng As Range
lastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
For i = lastCol To 4 Step -1
Select Case .Cells(2, i).Value
Case "C15", "C17", "C19", "C20", "C21", "C22", "C23", "C24", "C25", "C28", "C29", "C30", "C32"
' keep
Case Else
If rng Is Nothing Then
Set rng = .Columns(i)
Else
Set rng = Union(rng, .Columns(i))
End If
End Select
Next i
If Not rng Is Nothing Then
rng.Delete
End If
End With
End Sub

MS Excel For Each Loop: Insert Rows

I have a worksheet containing 242 rows. I want to create a new row beneath each existing one. Instead, my code creates 242 rows below row 1. I have spent all afternoon on Google and Stack Overflow and tried various ideas but get the same problem. Here's my code:
Function rws() As Integer
rws = (Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).row)
End Function
Sub InsRws()
Dim rng As Range
Dim row As Range
Set rng = Range("A1:A" & rws - 1)
For Each row In rng.Rows
Rows.Select
ActiveCell.Offset(1).EntireRow.Insert
Next row
End Sub
Maybe this will help
Function rws() As Integer
rws = (Cells(rows.Count, "A").End(xlUp).Offset(1, 0).row)
End Function
Sub InsRws()
Dim rowCount As Integer
Dim i As Integer
rowCount = rws
For i = 1 To rowCount
Range("A" + CStr(2 * i - 1)).Select
ActiveCell.Offset(1).EntireRow.Insert
Next
End Sub
Easiest way is to count up rather down down, like this
Sub InsertRows()
Dim rw As Long
With ActiveSheet
For rw = .Cells(.Rows.Count, 1).End(xlUp).Row To 2 Step -1
.Rows(rw).Insert
Next
End With
End Sub
If you debug in for each loop debug.print row.address you will notice your rng keeps expanding when there is an insert. Instead you can use for loop as in below code.
Sub InsRws()
Dim lastRow As Long
lastRow = Sheets("Sheet1").Range("A65000").End(xlUp).Row
For i = 1 To lastRow
Range("A" & i * 2).EntireRow.Insert
Next
End Sub

Resources