Delete rows with merged cells - excel

I found a procedure to highlight merged cells in an active sheet:
I tried a ActiveCell.EntireRow.Delete statement to delete the row that is currently iterated over.
Sub DeleteRows()
Dim x As Range
For Each x In ActiveSheet.UsedRange
If x.MergeCells Then
x.Interior.ColorIndex = 8
ActiveCell.EntireRow.Delete
End If
Next
End Sub
I don't care about highlighting the merged cells. The goal is to delete any row that has a merged cell.

Find out all merged cell ranges, club them and delete in one go.
Sub DeleteRows()
Dim x As Range
Dim rngDelete As Range
For Each x In ActiveSheet.UsedRange
If x.MergeCells Then
If rngDelete Is Nothing Then
Set rngDelete = x
Else
Set rngDelete = Union(rngDelete, x)
End If
End If
Next
If Not rngDelete Is Nothing Then
rngDelete.EntireRow.Delete
End If
End Sub

When deleting rows, always delete from the bottom up or a) you risk deleting the next cell you want to examine and b) you risk skipping over a row that comes up to take the place of a deleted row.
Sub DeleteRows()
Dim r as long, c as long
with ActiveSheet.UsedRange
'work backwards through the rows
For r = .rows.count to 1 step -1
'work forwards through the columns
For c = 1 to .columns.count
If .cells(r, c).MergeCells Then
'once a merged cell is found, delete then go immediately to the next row
.cells(r, c).EntireRow.Delete
exit for
End If
next c
Next r
end with
End Sub

A quick way to do this is to find all the merged cells then delete them in one go: a good way to do this is to use a range.find using a cells 'format' as merged then combine the found ranges
The following code loops through merged ranges and creates a union then selects the entire rows
Sub SelectMerge()
Dim rng As Range, rngUnion As Range, Test As Range
Dim ws As Worksheet: Set ws = ActiveSheet
With Application.FindFormat
.Clear
.MergeCells = True
End With
With ws.UsedRange
Set rng = .Find("", SearchFormat:=True)
Do
If Not rngUnion Is Nothing Then Set rngUnion = Application.Union(rng, rngUnion)
If rngUnion Is Nothing Then Set rngUnion = rng
If rng Is Nothing Then Exit Do
Set rng = .Find("", After:=rng, SearchFormat:=True)
Loop While Application.Intersect(rng, rngUnion) Is Nothing
End With
If Not rngUnion Is Nothing Then rngUnion.EntireRow.Select 'rngUnion.EntireRow.Delete
End Sub

Related

Delete rows Excel VBA within selected Cels

I would like to delete entire rows when cells are blank in column B, but I want to skip some of the cells. I managed to work out a code for the first part, but I want to skip two rows and then let the code delete the next part.
First part is B4:B13 and the next is B16:B27
Try the next code, please. It uses a discontinuous range (as you need) and delete all the rows at the end of the code, at once. Being very fast, even on big ranges:
Sub testDeleteRowsDiscontinuousRange()
Dim sh As Worksheet, lastRow As Long, C As Range, rngDel As Range
Dim rng As Range
Set sh = ActiveSheet ' use here your necessary sheet
lastRow = sh.Range("B" & Rows.count).End(xlUp).Row
Set rng = sh.Range("B4:B13,B16:B27")
For Each C In rng.cells
If C.Value = "" Then
If rngDel Is Nothing Then
Set rngDel = C
Else
Set rngDel = Union(rngDel, C)
End If
End If
Next C
If Not rngDel Is Nothing Then rngDel.EntireRow.Delete xlUp
End Sub

How to delete a row if there is no value in a column?

I'm trying to delete rows in table if there is no value in a certain column.
I've used a code that deletes rows if there is one cell value missing, but I would like to delete rows if a cell does not contain a value in a certain column.
For example, if there is no value in Column G Row 5 then I want to delete the entire row.
Sub Test2()
Dim rng As Range
On Error Resume Next
Set rng = Range("Table3").SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
If Not rng Is Nothing Then
rng.Delete Shift:=xlUp
End If
End Sub
This deletes all rows with any type of missing cell value.
Two small changes:
Sub Test2()
Dim rng As Range
On Error Resume Next
Set rng = Range("G:G").SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
If Not rng Is Nothing Then
rng.EntireRow.Delete Shift:=xlShiftUp
End If
End Sub
EDIT:
If you want to work directly with the table, then consider iterating over the ListRows of the table in question, something like this:
Sub Test2()
Dim myTbl As ListObject
Set myTbl = Sheet1.ListObjects("table3") ' change sheet as necessary
Dim indx As Long
indx = myTbl.ListColumns("ColumnName").Index
Dim rngToDelete As Range
Dim myRw As ListRow
For Each myRw In myTbl.ListRows
If IsEmpty(myRw.Range(1, indx).Value) Then
If rngToDelete Is Nothing Then
Set rngToDelete = myRw.Range
Else
Set rngToDelete = Union(rngToDelete, myRw.Range)
End If
End If
Next myRw
If Not rngToDelete Is Nothing Then
rngToDelete.Delete Shift:=xlShiftUp
End If
End Sub
Note: Technically, it's xlShiftUp, not xlUp.

VBA macro delete cells containing #N/A and shift up the cells (not the rows)

I'm creating a ranking and I need to delete all the cells with #N/A (pasted as text, not formula) and to delete those cells and shhift them up.
The worksheet contains 503 raws and I need it from column A to T.
Thanks in advance, I have tried so many VBA codes of this web and I'm not able to find something that works.
Try,
dim rng as range
with worksheets("sheet1")
on error resume next
set rng = .range("A:T").specialcells(xlcelltypeformulas, xlerrors)
if not rng is nothing then
rng.delete shift:=xlup
end if
set rng = .range("A:T").specialcells(xlcelltypeconstants, xlerrors)
if not rng is nothing then
rng.delete shift:=xlup
end if
on error goto 0
end with
This should work. There are faster ways of doing what you ask, but since you don't have that big of a data set, I just modified some code I had available.
Sub KillPoundNa()
Dim rCell As Range, WS As Worksheet, KillRng As Range, UndesireableText As String
UndesireableText = "#N/A"
Set WS = ActiveSheet
Set KillRng = WS.Cells(Rows.Count, 1)
For Each rCell In WS.UsedRange.Cells
If InStr(1, rCell.Text, UndesireableText, vbTextCompare) > 0 Then
Set KillRng = Union(KillRng, rCell)
End If
Next rCell
KillRng.Delete (xlUp)
End Sub

Evaluate a list of values in a column against a combobox value most efficiently

I am trying to delete duplicate values in a temporary list based on a value in a combobox. The code below loops through individual rows to check whether a value matches. It is slow.
Dim ws As Worksheet
Dim i As Long
Set ws = Sheets("TempList3")
On Error Resume Next
For i = Cells(Rows.Count, 2).End(xlUp).Row To 1 Step -1
If Cells(i, 2) <> Sheets("Sheet1").ComboBox2.Value Then
ws.Rows(i).EntireRow.Delete
End If
Next
Is there a way to evaluate the entire column's values against the combobox's value once and then delete all rows on a worksheet. Or perhaps there is a better way?
I used a looping Find function, it deletes the row where the value was found and then it searches again and deletes the next row it finds until it can no longer find the Combo value on the sheet:
Sub find_cell()
Dim find_cell As Range
Set ws = Sheets("TempList3")
stop_loop = False
Do Until stop_loop = True
Set find_cell = ws.Cells.Find(What:=Sheets("Sheet1").ComboBox2.Value, LookAt:=xlWhole)
If Not find_cell Is Nothing Then
ws.Rows(find_cell.Row).EntireRow.Delete
Else
stop_loop = True
End If
Loop
End Sub
Not knowing how many rows you are talking about, I used 10 thousand for my example codes. here are two examples, try the both and see what works best for you.
You can run through the column and unionize the range found, then delete the rows, for example.
See here for example workbook
Sub UnIonRng()
Dim FrstRng As Range
Dim UnIonRng As Range
Dim c As Range, s As String
s = Sheets("Sheet1").ComboBox2
Set FrstRng = Range("B:B").SpecialCells(xlCellTypeConstants, 23)
For Each c In FrstRng.Cells
If c = s Then
If Not UnIonRng Is Nothing Then
Set UnIonRng = Union(UnIonRng, c) 'adds to the range
'MsgBox UnionRng.Address 'remove later
Else
Set UnIonRng = c
End If
End If
Next c
UnIonRng.EntireRow.Delete
End Sub
Or you can try to filter the column B and delete the rows that way:
Sub FilterDeleteRow()
Dim ws As Worksheet
Dim LstRw As Long, Rng As Range, s As String, x
Set ws = Sheets("TempList3")
s = Sheets("Sheet1").ComboBox2
Application.ScreenUpdating = 0
With ws
LstRw = .Cells(.Rows.Count, "B").End(xlUp).Row
x = Application.WorksheetFunction.CountIf(.Range("B:B"), s)
If x > 0 Then
Columns("B:B").AutoFilter Field:=1, Criteria1:=s
Set Rng = .Range("B2:B" & LstRw).SpecialCells(xlCellTypeVisible)
Rng.EntireRow.Delete
.AutoFilterMode = 0
Else: MsgBox "Not Found"
End If
End With
End Sub

Looping through sheets to delete certain cells

I wish to delete specific cells from the sheets in a workbook. While doing so it should also delete specific cells having formula error in these worksheets of the workbook.
I used a recent program in stackoverflow by #Blind Seer as per following link which is for similar applications.
incorporating-sheet-loop
Sample of workbook sheets before program run are appended below
Code adopted by me as follows.
Sub DeleteCells()
Dim rng As Range, rngError As Range, delRange As Range
Dim i As Long, j As Long, k As Long
Dim wks As Worksheet
On Error Resume Next
Set rng = Application.InputBox("Select cells To be deleted", Type:=8)
On Error GoTo 0
If rng Is Nothing Then Exit Sub Else rng.Delete
For k = 1 To ThisWorkbook.Worksheets.Count 'runs through all worksheets
Set wks = ThisWorkbook.Worksheets(k)
With wks
For i = 1 To 7 '<~~ Loop trough columns A to G
'~~> Check if that column has any errors
On Error Resume Next
Set rngError = .Columns(i).SpecialCells(xlCellTypeFormulas, xlErrors)
On Error GoTo 0
If Not rngError Is Nothing Then
For j = 1 To 100 '<~~ Loop Through rows 1 to 100
If .Cells(j, i).Text = "#DIV/0!" Then
'~~> Store The range to be deleted
If delRange Is Nothing Then
Set delRange = .Columns(i)
Exit For
Else
Set delRange = Union(delRange, .Columns(i))
End If
End If
Next j
End If
Next i
End With
Next k
'~~> Delete the range in one go
If Not delRange Is Nothing Then delRange.Delete
End Sub
After running the code it deletes the cell input in the input box ie it blanks out the data in the cell and append rest of the data in the row at the end of the last filled row. It is not blanking out error cells and the program gives the error message:
Method 'Union of object_Global failed
on the following code line
'Set delRange = Union(delRange, .Columns(i))'
Sample data after proram run is appended below.
Please help in locating the error in the program. Result desired is Input cell range should blank out retaining its row position. Same also for error cells.
Thanks
Option Explicit
Sub DeleteCells()
Dim ws As Worksheet, rng As Range, rngErr As Range
On Error Resume Next
Set rng = Application.InputBox("Select cells to be deleted", Type:=8)
If Not rng Is Nothing Then
rng.Delete
For Each ws In ThisWorkbook.Worksheets
Set rngErr = ws.UsedRange.SpecialCells(xlCellTypeFormulas, xlErrors)
If Not rngErr Is Nothing Then rngErr.Clear
Next
End If
End Sub
Not much of a solution but the reason for the error is that Union does not work across worksheets. It will work for ranges on a single sheet.
You could adapt your code to work one sheet at a time:
Sub DeleteCells()
Dim rng As Range, rngError As Range, delRange As Range
Dim i As Long, j As Long, k As Long
Dim wks As Worksheet
On Error Resume Next
Set rng = Application.InputBox("Select cells To be deleted", Type:=8)
On Error GoTo 0
If rng Is Nothing Then Exit Sub Else rng.Delete
For k = 1 To ThisWorkbook.Worksheets.Count 'runs through all worksheets
'Set wks = ThisWorkbook.Worksheets(k)
'With wks
With ThisWorkbook.Worksheets(k) '<<do each sheet individually so that Union functions as expected
For i = 1 To 7 '<~~ Loop trough columns A to G
'~~> Check if that column has any errors
On Error Resume Next
Set rngError = .Columns(i).SpecialCells(xlCellTypeFormulas, xlErrors)
On Error GoTo 0
If Not rngError Is Nothing Then
For j = 1 To 100 '<~~ Loop Through rows 1 to 100
If .Cells(j, i).Text = "#DIV/0!" Then
'~~> Store The range to be deleted
If delRange Is Nothing Then
Set delRange = .Columns(i)
Exit For
Else
Set delRange = Union(delRange, .Columns(i))
End If
End If
Next j
End If
Next i
End With
Next k
'~~> Delete the range in one go
If Not delRange Is Nothing Then delRange.Delete
End Sub
You can use IsNumeric to check if the cells contain numeric values. Errors are not numeric values, so IsNumeric(Cell with error) = False. I modified your code:
Set wks = ThisWorkbook.Worksheets(k)
With wks
For i = 1 To 7 '<~~ Loop trough columns A to G
'~~> Check if that column has any errors
On Error Resume Next
Set rngError = .Columns(i).SpecialCells(xlCellTypeFormulas, xlErrors)
On Error GoTo 0
If Not rngError Is Nothing Then
For j = 1 To 100 '<~~ Loop Through rows 1 to 100
If Not IsNumeric(.Cells(j, i)) Then
'~~> Store The range to be deleted
If delRange Is Nothing Then
Set delRange = .Columns(i)
Exit For
Else
Set delRange = Union(delRange, .Columns(i))
End If
End If
Next j
End If
Next i
End With
Next k
'~~> Delete the range in one go
If Not delRange Is Nothing Then delRange.Delete
End Sub
Note: This means that if sometimes text is to be entered, it will count it as an ERROR. So be careful if that's the case!
Also, as per my comment; If your cells are quotients of cells on other cells, consider using this instead of code; support.microsoft.com/en-us/kb/182188. To simply skip the divisions.

Resources