Хитрости »
28 Май 2011 644788 просмотров
Как удалить строки по условию?
Предположу, что почти каждый сталкивался с ситуацией, когда необходимо удалить только определенные строки: имеется большая таблица и необходимо удалить из неё только те строки, которые содержат какое-то слово (цифру, фразу). Для выполнения подобной задачи можно воспользоваться несколькими способами.
Способ первый:
Использовать встроенное средство Excel — фильтр. Сначала его необходимо «установить» на листе:
- Выделяем таблицу с данными, включая заголовки. Если их нет — то выделяем с самой первой строки таблицы, в которой необходимо удалить данные
- устанавливаем фильтр:
- для Excel 2003: Данные—Фильтр—Автофильтр
- для Excel 2007-2010: вкладка Данные(Data) —Фильтр(Filter)(или вкладка Главная(Home) —Сортировка и фильтр(Sort&Filter) —Фильтр(Filter))
Теперь выбираем условие для фильтра:
- в Excel 2003 надо выбрать Условие и в появившейся форме выбрать непосредственно условие(«равно», «содержит», «начинается с» и т.д.), а напротив значение в соответствии с условием.
- Для 2007-2010 Excel нужно выбрать Текстовые фильтры(Text Filters) и либо сразу выбрать одно из предлагаемых условий, либо нажать Настраиваемый фильтр(Custom Filter) и ввести значения для отбора в форме
После этого удалить отфильтрованные строки. В 2007 Excel могут возникнуть проблемы с удалением отфильтрованных строк, поэтому рекомендую сначала так же прочитать статью: Excel удаляет вместо отфильтрованных строк — все?! Как избежать.
Способ второй:
применить код VBA, который потребует только указания значения, которое необходимо найти в строке и номер столбца, в котором искать значение.
Sub Del_SubStr() Dim sSubStr As String 'искомое слово или фраза(может быть указанием на ячейку) Dim lCol As Long 'номер столбца с просматриваемыми значениями Dim lLastRow As Long, li As Long Dim lMet As Long Dim arr sSubStr = InputBox("Укажите значение, которое необходимо найти в строке", "www.excel-vba.ru", "") If sSubStr = "" Then lMet = 0 Else lMet = 1 lCol = Val(InputBox("Укажите номер столбца, в котором искать указанное значение", "www.excel-vba.ru", 1)) If lCol = 0 Then Exit Sub lLastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count arr = Cells(1, lCol).Resize(lLastRow).Value Application.ScreenUpdating = 0 Dim rr As Range For li = 1 To lLastRow 'цикл с первой строки до конца If -(InStr(arr(li, 1), sSubStr) > 0) = lMet Then If rr Is Nothing Then Set rr = Cells(li, 1) Else Set rr = Union(rr, Cells(li, 1)) End If End If Next li If Not rr Is Nothing Then rr.EntireRow.Delete Application.ScreenUpdating = 1 End Sub
Если значение sSubStr не будет указано, то будут удалены строки, ячейки указанного столбца которых, пустые.
Данный код необходимо поместить в стандартный модуль. Вызвать с листа его можно нажатием клавиш Alt+F8, после чего выбрать Del_SubStr и нажать Выполнить. Если в данном коде в строке
If -(InStr(Cells(li, 1), sSubStr) > 0) = lMet Then
вместо = lMet указать <> lMet, то удаляться будут строки, не содержащие указанное для поиска значение. Иногда тоже удобно.
Но. Данный код просматривает строки на предмет частичного совпадения указанного значения. Например, если Вы укажете текст для поиска «отчет», то будут удалены все строки, в которых встречается это слово(«квартальный отчет», «отчет за месяц» и т.д.). Это не всегда нужно. Поэтому ниже приведен код, который будет удалять только строки, указанные ячейки которых равны конкретно указанному значению:
Sub Del_SubStr() Dim sSubStr As String 'искомое слово или фраза(может быть указанием на ячейку) Dim lCol As Long 'номер столбца с просматриваемыми значениями Dim lLastRow As Long, li As Long Dim arr sSubStr = InputBox("Укажите значение, которое необходимо найти в строке", "www.excel-vba.ru", "") lCol = Val(InputBox("Укажите номер столбца, в котором искать указанное значение", "www.excel-vba.ru", 1)) If lCol = 0 Then Exit Sub lLastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count arr = Cells(1, lCol).Resize(lLastRow).Value Application.ScreenUpdating = 0 Dim rr As Range For li = 1 To lLastRow 'цикл с первой строки до конца If CStr(arr(li, 1)) = sSubStr Then If rr Is Nothing Then Set rr = Cells(li, 1) Else Set rr = Union(rr, Cells(li, 1)) End If End If Next li If Not rr Is Nothing Then rr.EntireRow.Delete Application.ScreenUpdating = 1 End Sub
Здесь так же, как и в случае с предыдущим кодом можно заменить оператор сравнения(Cells(li, lCol) = sSubStr) с равно на неравенство(Cells(li, lCol) <> sSubStr) и тогда удаляться будут строки, значения ячеек которых не равно указанному.
УДАЛЕНИЕ СТРОК НА ОСНОВАНИИ СПИСКА ЗНАЧЕНИЙ(МНОЖЕСТВЕННЫЕ КРИТЕРИИ)
Иногда бывают ситуации, когда необходимо удалить строки не по одному значению, а по нескольким. Например, если строка содержит или Итог или Отчет. Ниже приведен код, при помощи которого можно удалить строки, указав в качестве критерия диапазон значений.
Значения, которые необходимо найти и удалить перечисляются на листе с именем «Лист2». Т.е. указав на «Лист2» в столбце А(начиная с первой строки) несколько значений — они все будут удалены. Если лист называется иначе(скажем «Соответствия») в коде необходимо будет «Лист2» заменить на «Соответствия». Удаление строк происходит на активном в момент запуска кода листе. Это значит, что перед запуском кода надо перейти на тот лист, строки в котором необходимо удалить.
Sub Del_Array_SubStr() Dim sSubStr As String 'искомое слово или фраза Dim lCol As Long 'номер столбца с просматриваемыми значениями Dim lLastRow As Long, li As Long Dim avArr, lr As Long Dim arr lCol = Val(InputBox("Укажите номер столбца, в котором искать указанное значение", "www.excel-vba.ru", 1)) If lCol = 0 Then Exit Sub Application.ScreenUpdating = 0 lLastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count 'заносим в массив значения листа, в котором необходимо удалить строки arr = Cells(1, lCol).Resize(lLastRow).Value 'Получаем с Лист2 значения, которые надо удалить в активном листе With Sheets("Лист2") 'Имя листа с диапазоном значений на удаление avArr = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp)) End With 'удаляем Dim rr As Range For lr = 1 To UBound(avArr, 1) sSubStr = avArr(lr, 1) For li = 1 To lLastRow 'цикл с первой строки до конца If CStr(arr(li, 1)) = sSubStr Then If rr Is Nothing Then Set rr = Cells(li, 1) Else Set rr = Union(rr, Cells(li, 1)) End If End If DoEvents Next li DoEvents Next lr If Not rr Is Nothing Then rr.EntireRow.Delete Application.ScreenUpdating = 1 End Sub
Чтобы код выше удалял строки не по точному совпадению слов, а по частичному(например, в ячейке записано «Привет, как дела?», а в списке есть слово «привет» — надо удалить, т.к. есть слово «привет»), то надо строку:
If CStr(arr(li, 1)) = sSubStr Then
заменить на такую:
If InStr(1, arr(li, 1), sSubStr, 1) > 0 Then
УДАЛЕНИЕ ИЗ ЛИСТА СТРОК, КОТОРЫХ НЕТ В СПИСКЕ ЗНАЧЕНИЙ(МНОЖЕСТВЕННЫЕ КРИТЕРИИ)
Т.к. в последнее время стало поступать все больше и больше вопросов как не удалять значения по списку, а наоборот — оставить в таблице только те значения, которые перечислены в списке — решил дополнить статью и таким кодом.
Значения, которые необходимо оставить перечисляются на листе с именем «Лист2». Т.е. указав на «Лист2» в столбце А(начиная с первой строки) несколько значений — после работы кода на листе будут оставлены только те строки, в которых присутствует хоть одно из перечисленных в списке значений. Если лист называется иначе(скажем «Соответствия») в коде необходимо будет «Лист2» заменить на «Соответствия». Удаление строк происходит на активном в момент запуска кода листе. Это значит, что перед запуском кода надо перейти на тот лист, строки в котором необходимо удалить.
В отличие от приведенных выше кодов, данный код ориентирован на то, что значения в списке указаны не полностью. Т.е. если необходимо оставить только те ячейки, в которых встречается слово «активы», то в списке надо указать только это слово. В этом случае если в ячейке будет записана фраза «Нематериальные активы» или «Активы сторонние» — эти ячейки не будут удалены, т.к. в них встречается слово «активы». Регистр букв при этом неважен.
'процедура оставляет в листе только те значения, которые перечислены в списке Sub LeaveOnlyFoundInArray() Dim sSubStr As String 'искомое слово или фраза Dim lCol As Long 'номер столбца с просматриваемыми значениями Dim lLastRow As Long, li As Long Dim avArr, lr As Long Dim arr Dim IsFind As Boolean lCol = Val(InputBox("Укажите номер столбца, в котором искать указанное значение", "www.excel-vba.ru", 1)) If lCol = 0 Then Exit Sub Application.ScreenUpdating = 0 lLastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count 'заносим в массив значения листа, в котором необходимо удалить строки arr = Cells(1, lCol).Resize(lLastRow).Value 'Получаем с Лист2 значения, которые надо удалить в активном листе With Sheets("Лист2") 'Имя листа с диапазоном значений на удаление avArr = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp)) End With 'удаляем Dim rr As Range For li = 1 To lLastRow 'цикл с первой строки таблицы до конца IsFind = False For lr = 1 To UBound(avArr, 1) 'цикл по списку значений на удаление sSubStr = avArr(lr, 1) If InStr(1, arr(li, 1), sSubStr, 1) > 0 Then IsFind = True End If DoEvents Next lr 'если значение таблицы не найдено в списке - удаляем строку If Not IsFind Then If rr Is Nothing Then Set rr = Cells(li, 1) Else Set rr = Union(rr, Cells(li, 1)) End If End If DoEvents Next li If Not rr Is Nothing Then rr.EntireRow.Delete Application.ScreenUpdating = 1 End Sub
Чтобы код выше сравнивал значения таблицы со значениями списка по точному совпадению слов, а не по частичному, то надо строку:
If InStr(1, arr(li, 1), sSubStr, 1) > 0 Then
заменить на такую:
If CStr(arr(li, 1)) = sSubStr Then
Для всех приведенных кодов можно строки не удалять, а скрывать. Для этого надо строку:
If Not rr Is Nothing Then rr.EntireRow.Delete
заменить на такую:
If Not rr Is Nothing Then rr.EntireRow.Hidden = True
По умолчанию все коды начинают просмотр строк с первой по последнюю заполненную на листе. И если необходимо удалять строки не с первой или не по последнюю, то надо внести корректировки в эту строку:
For li = 1 To lLastRow 'цикл с первой строки до конца
1 — это первая строка; lLastRow — определяется автоматически кодом и равна номеру последней заполненной строки на листе. Если надо начать удалять строки только с 7-ой строки(например, в первых 6-ти шапка), то код будет выглядеть так:
For li = 7 To lLastRow 'цикл с седьмой строки до конца
А если надо удалять только с 3-ей по 300-ю, то код будет выглядеть так:
For li = 3 To 300 'цикл с третьей строки до трехсотой
Так же см.:
Что такое макрос и где его искать?
Что такое модуль? Какие бывают модули?
Как создать кнопку для вызова макроса на листе
Удаление всех пустых строк в таблице
Удаление пустых столбцов на листе
Установить Быстрый фильтр
Фильтр
Статья помогла? Поделись ссылкой с друзьями!
Видеоуроки
Поиск по меткам
Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика
Jordan07
Пользователь
Сообщений: 39
Регистрация: 18.06.2019
Добрый день!
Прошу помочь дописать макрос по удалению не нужных строк
Требуется удалить строки, которые не содержат определенный текст, т.е. в столбце 9 нужно проверить, содержит ли ячейка одно из значений текста (ду, му00, абк, атс, гств, удтс, тдчс, пмп), и если нет, то ее удалить.
Моих знаний хватило, чтобы написать простой код:
Код |
---|
Dim Пример As Worksheet Set Пример = Worksheets("Пример") Row = Пример.Cells(Rows.Count, 1).End(xlUp).Row For i = 2 To Row If InStr(1, Пример.Cells(i, 9), "ду") Or InStr(1, Пример.Cells(i, 9), "му00") Or InStr(1, Пример.Cells(i, 9), "абк") _ Or InStr(1, Пример.Cells(i, 9), "гств") Or InStr(1, Пример.Cells(i, 9), "удтс") Or InStr(1, Пример.Cells(i, 9), "тдчс") _ Or InStr(1, Пример.Cells(i, 9), "атс") Then Else Rows(i).Delete End If Next i |
Но строк, для проверки, очень много (около 100 тыс.), поэтому макрос отрабатывает очень долго
У меня есть код, который ускоряет процесс
Код |
---|
Dim arrKey(), arr(), arrS() Dim lRow&, i&, iKey, iTemp Dim myRng As Range, delRows As Range Dim Пример As Worksheet Set Пример = Worksheets("Пример") arrKey = Array("ду", "му00", "абк", "атс", "гств", "удтс", "тдчс", "пмп") With Worksheets("Пример") Set myRng = .Range(.Cells(2, 1), Cells(.Cells(Rows.Count, 1).End(xlUp).Row, .Cells(2, .Columns.Count).End(xlToLeft).Column)) arr = myRng.Value End With ReDim arrNew(1 To UBound(arr, 1), 1 To UBound(arr, 2)) With CreateObject("Scripting.Dictionary") For Each iKey In arrKey iTemp = .Item(iKey) Next For i = 1 To UBound(arr, 1) If Not .Exists(arr(i, 9)) Then If delRows Is Nothing Then Set delRows = myRng.Rows(i) Else Set delRows = Union(delRows, myRng.Rows(i)) End If End If Next End With If Not delRows Is Nothing Then delRows.Delete |
Но удаляются все строки, и как я понимаю, проблема в строке
Код |
---|
arrKey = Array("ду", "му00", "абк", "атс", "гств", "удтс", "тдчс", "пмп") |
По ней ищется конкретное значение в ячейке, и макрос его не находит, поэтому удаляет все строки, а мне нужно, чтобы он искал содержится ли в ячейке данная часть текста и если нет, то удалить
Подскажите пожалуйста, как правильно записать данную строку (или заменить ее)? Возможно нужно какой-то символ поставить, но к сожалению я не нашел ответа в интернете(
Прикрепленные файлы
- Пример.xlsm (25.56 КБ)
Изменено: Jordan07 — 25.05.2021 13:40:54
макрос удалит на листе все строки, в которых содержится искомый текст:
(пример — во вложении ConditionalRowsDeleting.xls)
Sub УдалениеСтрокПоУсловию() Dim ra As Range, delra As Range, ТекстДляПоиска As String Application.ScreenUpdating = False ' отключаем обновление экрана ТекстДляПоиска = "Наименование ценности" ' удаляем строки с таким текстом ' перебираем все строки в используемом диапазоне листа For Each ra In ActiveSheet.UsedRange.Rows ' если в строке найден искомый текст If Not ra.Find(ТекстДляПоиска, , xlValues, xlPart) Is Nothing Then ' добавляем строку в диапазон для удаления If delra Is Nothing Then Set delra = ra Else Set delra = Union(delra, ra) End If Next ' если подходящие строки найдены - удаляем их If Not delra Is Nothing Then delra.EntireRow.Delete End Sub
Чтобы вместо удаления просто скрыть такие строки, замените строку
If Not delra Is Nothing Then delra.EntireRow.Delete
на
If Not delra Is Nothing Then delra.EntireRow.Hidden=TRUE
Расширенная версия этого макроса — с использованием UserForm для ввода искомого значения
Function ПоискСтрокПоУсловию(ByVal ТекстДляПоиска As String, Optional HideOnly As Boolean) As Long ' функция получает в качестве параметра ТекстДляПоиска (можно использовать символы * и ?) ' Если HideOnly = TRUE, то строки, содержащие в ячейках ТекстДляПоиска, скрываются, ' иначе (HideOnly = FALSE - по умолчанию) - удаляются ' Функция возвращает количество удалённых строк Dim ra As Range, delra As Range Application.ScreenUpdating = False ' отключаем обновление экрана ' перебираем все строки в используемом диапазоне листа For Each ra In ActiveSheet.UsedRange.Rows ' если в строке найден искомый текст If Not ra.Find(ТекстДляПоиска, , xlValues, xlPart) Is Nothing Then ' добавляем строку в диапазон для удаления If delra Is Nothing Then Set delra = ra Else Set delra = Union(delra, ra) End If Next On Error Resume Next: ПоискСтрокПоУсловию = delra.Areas.Count ' количество найденных строк If Not delra Is Nothing Then ' если подходящие строки найдены - скрываем или удаляем их If HideOnly Then delra.EntireRow.Hidden = True Else delra.EntireRow.Delete End If End Function
Ещё один вариант кода, позволяющего выполнять поиск (с последующим удалением или скрытием строк) сразу по нескольким условиям:
Sub УдалениеСтрокПоНесколькимУсловиям() Dim ra As Range, delra As Range Application.ScreenUpdating = False ' отключаем обновление экрана ' ищем и удаляем строки, содержащие заданный текст ' (можно указать сколько угодно значений, и использовать подстановочные знаки) УдалятьСтрокиСТекстом = Array("Наименование *", "Количество", _ "текст?", "цен*сти", "*78*") ' перебираем все строки в используемом диапазоне листа For Each ra In ActiveSheet.UsedRange.Rows ' перебираем все фразы в массиве For Each word In УдалятьСтрокиСТекстом ' если в очередной строке листа найден искомый текст If Not ra.Find(word, , xlValues, xlPart) Is Nothing Then ' добавляем строку в диапазон для удаления If delra Is Nothing Then Set delra = ra Else Set delra = Union(delra, ra) End If Next word Next ' если подходящие строки найдены, то: (оставьте одну из 2 следующих строк) If Not delra Is Nothing Then delra.EntireRow.Hidden = True ' скрываем их If Not delra Is Nothing Then delra.EntireRow.Delete ' удаляем их End Sub
5 / 5 / 0 Регистрация: 27.02.2013 Сообщений: 115 |
|
1 |
|
Поиск определенного текста в столбце(строке) и удаление всей строки12.11.2015, 00:03. Показов 9043. Ответов 15
Друзья, подскажите, пожалуйста, как в определенном столбце найти определенный текст и удалить все строки содержащие этот текст. Или не обязательно искать в определенном столбце определенный текст а просто найти определенный текст во всем листе и удалить строки содержащие этот текст.
0 |
Michael99 190 / 59 / 20 Регистрация: 16.07.2013 Сообщений: 234 |
||||
12.11.2015, 00:41 |
2 |
|||
Измените адрес вашего определенного столбца или найдите его через find Добавлено через 10 минут
1 |
5 / 5 / 0 Регистрация: 27.02.2013 Сообщений: 115 |
|
12.11.2015, 16:48 [ТС] |
3 |
Что-то он не работает, вы ничего не могли пропустить?
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
12.11.2015, 17:35 |
4 |
currentregion тут совершеено не годится — Идите просто циклом по определённому столбцу снизу вверх, ну или можно искать через Find до тех пор, пока будет находиться определённый текст.
0 |
5 / 5 / 0 Регистрация: 27.02.2013 Сообщений: 115 |
|
13.11.2015, 08:03 [ТС] |
5 |
Честно говоря не сообразил как в итоге должен изменится код. Hugo121, можете написать свой вариант?
0 |
3827 / 2254 / 751 Регистрация: 02.11.2012 Сообщений: 5,930 |
|
13.11.2015, 09:22 |
6 |
можете написать свой вариант? может и не только Hugo121, но и многие другие при наличии вашего файла и описания согласно файла.
0 |
Michael99 190 / 59 / 20 Регистрация: 16.07.2013 Сообщений: 234 |
||||
13.11.2015, 11:17 |
7 |
|||
Извините прошлый код не было возможности подправить, сделал новый с учётом замечаний от Hugo, у меня работает
1 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
13.11.2015, 11:29 |
8 |
все строки содержащие этот текст — тут ведь не написано, что в этих «строках» нет и другого текста!
0 |
5 / 5 / 0 Регистрация: 27.02.2013 Сообщений: 115 |
|
13.11.2015, 20:01 [ТС] |
9 |
Michael99, работает, но как-то не так. Удаляет только в столбце А все строки за исключением первой строки. При попытке замены на другой столбец в строке №8 допустим не A1 а D1 все равно удаляет только в столбце A1. Где надо править чтобы удалял в столбце D1? И почему не удаляется первая строка? Добавлено через 19 минут
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
13.11.2015, 20:32 |
10 |
в строе конечно есть другой текст
находим в столбце А все строки содержащие слово «красный» понимай как хочешь — хошь так, хошь эдак… Ведь вроде как «работает, но как-то не так» код, который проверяет не на «содержит», а на «удаляю только тогда, когда никакого другого текста тут нет».
0 |
5 / 5 / 0 Регистрация: 27.02.2013 Сообщений: 115 |
|
13.11.2015, 23:03 [ТС] |
11 |
Хорошо, разберем на реальном примере. В данном файле необходимо удалить строки содержащие слово красный. Поиск необходимо выполнять по столбцу А. В файле код от Michael99. На данный момент он удаляет все корректно, но первая строка почему-то не удаляется.
0 |
Казанский 15136 / 6410 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
||||
13.11.2015, 23:31 |
12 |
|||
run82, автофильтр не рулит?
1 |
Hugo121 6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
||||
14.11.2015, 00:28 |
13 |
|||
Если строк не очень много — то возможен такой экзотический вариант:
Хотя может в свежих версиях и нет уже ограничений по количеству несвязных диапазонов в ColumnDifferences, не знаю…
2 |
Michael99 190 / 59 / 20 Регистрация: 16.07.2013 Сообщений: 234 |
||||
14.11.2015, 09:40 |
14 |
|||
Сообщение было отмечено run82 как решение РешениеДобавлено через 23 минуты Добавлено через 42 минуты
1 |
5 / 5 / 0 Регистрация: 27.02.2013 Сообщений: 115 |
|
15.11.2015, 19:13 [ТС] |
15 |
Michael99, спасибо большое. Все работает как надо. Вот только не понимаю назначение строки 12, такое ощущение, что она не нужна. Какие значения в ней не ставь все равно работает. Поясните?
0 |
3827 / 2254 / 751 Регистрация: 02.11.2012 Сообщений: 5,930 |
|
15.11.2015, 19:48 |
16 |
не понимаю назначение строки 12 она зависит от версии офиса. на работу кода не влияет.
1 |
Getting rid of specific cells could prove challenging if you were to do it manually. In this article, we’re going to show you how to make Excel delete rows with value of your choosing, using VBA. You can remove cells with certain strings or create an input cell where you can enter a value to select which cells to remove.
A VBA code to do this will consist of 2 parts: determining the variables, and deleting the rows that where the condition is met. We present you 2 alternative approaches for both parts.
Variables
The variables are the range that test will be applied and the condition itself. You can choose to determine these variables by entering them in the code or create an input section to let the users do this. Entering a static value into the code is easier if you’re consistently working with same range. On the other hand, if range changes, users will have to update the code every time. Here are both approaches for the range F3:F16 and condition the text set to «No»:
Static variable in the code:
Set condition_range = Range("F3:F16")
condition = "No"
Dynamic variable through user input:
Set condition_range = Application.InputBox(Prompt:="Please select the range that condition will be tested:", Type:=8)
condition = Application.InputBox(Prompt:="Please type the condition text:")
Here, the user entries can be collected with the Application.InputBox control and we must also set the Type argument to 8 to select all ranges. If the Type argument is omitted, the default input type will be Text.
We recommend using an error handling method in your code to handle the case of a user pressing Cancel in the InputBox instead of providing the requested information. Our error handling approach uses 3 types of code blocks:
Error handling part before End Sub:
error_handling:
MsgBox ("Process is canceled.") 'Explanatory message for end-user
End Sub
Move the process to error handling code part:
On Error GoTo error_handling
Reset error handling procedure:
On Error GoTo 0
Rows
You have 2 options to determine the rows to be deleted. You can either perform a loop through the rows and apply a logical condition test, or use the VBA support of the AutoFilter feature to filter the rows that meet the condition. The decision criteria between two approaches will determine whether the data will be kept.
The AutoFilter feature won’t work if your range is defined as an Excel Table. As a result, we suggest you to return your table into a regular range before running AutoFilter code. On the other hand, if your data spans over thousands of rows, looping through rows will require more computer resources and take longer to process. Let’s see code blocks for both approaches:
Looping through rows:
With condition_range
For i = .SpecialCells(xlCellTypeLastCell).Row To .Row Step -1If Cells(i, .Column) = condition Then Rows(i).EntireRow.Delete
Next i
End With
AutoFilter:
condition_range.AutoFilter Field:=1, Criteria1:=condition
Rows(condition_range.EntireRow.Address).Delete Shift:=xlUp
First, you need to add the module into the workbook or the add-in file. Copy and paste the code into the module to run it. The main advantage of the module method is that it allows saving the code in the file, so that it can be used again later. Furthermore, the subroutines in modules can be used by icons in the menu ribbons or keyboard shortcuts. Remember to save your file in either XLSM or XLAM format to save your VBA code.
Delete rows by a static condition with loop
Sub DeleteRowsByStaticCondition_Loop()
'defining variablesDim condition_range As Range
Dim condition As String
Dim i As Integer
'populating variables
Set condition_range = Range("F:F")
condition = "No"
'loop through rows and test the condition
With condition_range
For i = Cells(.SpecialCells(xlCellTypeLastCell).Row, .Column).Row To 1 Step -1
If Cells(i, .Column) = condition Then Rows(i).EntireRow.Delete
Next i
End With
End Sub
Delete rows by a dynamic condition with loop
Sub DeleteRowsByUserCondition_Loop()
'defining variablesDim condition_range As Range
Dim condition As String
Dim i As Integer
'error handling for Cancel buttons of InputBox controls
On Error GoTo error_handling
'populating variables
Set condition_range = Application.InputBox(Prompt:="Please select the range that condition will be tested:", Type:=8)
condition = Application.InputBox(Prompt:="Please type the condition text:")
'reset error handling procedure
On Error GoTo 0
'loop through rows and test the condition
With condition_range
For i = .SpecialCells(xlCellTypeLastCell).Row To .Row Step -1
If Cells(i, .Column) = condition Then Rows(i).EntireRow.Delete
Next i
End With
'exit sub without running error handling codes
Exit Sub
'error handling
error_handling:
MsgBox ("Process is canceled.") 'Explanatory message for end-user
End Sub
Delete rows by a static condition with AutoFilter
Sub DeleteRowsByStaticCondition_AutoFilter()
'defining variablesDim condition_range As Range
Dim condition As String
'populating variables
Set condition_range = Range("$F:$F")
condition = "No"
'applying AutoFilter
condition_range.AutoFilter Field:=1, Criteria1:=condition
'deleting filtered rows, remaining rows will be shifted to up
Rows(condition_range.EntireRow.Address).Delete Shift:=xlUp
'removing AutoFilter
On Error Resume Next
ActiveSheet.condition_range.ShowAllData
'selecting a cell for end-user
condition_range.Cells(1, 1).Select
End Sub
Delete rows by a dynamic condition with AutoFilter
Sub DeleteRowsByUserCondition_AutoFilter()
'defining variablesDim condition_range As Range
Dim condition As String
'populating variables
Set condition_range = Application.InputBox(Prompt:="Please select the range that condition will be tested:", Type:=8)
condition = Application.InputBox(Prompt:="Please type the condition text:")
'applying AutoFilter
condition_range.AutoFilter Field:=1, Criteria1:=condition
'deleting filtered rows, remaining rows will be shifted to up
Rows(condition_range.EntireRow.Address).Delete Shift:=xlUp
'removing AutoFilter
On Error Resume Next
ActiveSheet.condition_range.ShowAllData
'selecting a cell for end-user
condition_range.Cells(1, 1).Select
End Sub
Найти и удалить строки макросом |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
Чтобы быстро удалить или удалить несколько строк на основе значения ячейки в Excel, вам может потребоваться сначала выделить эти целые строки, содержащие определенное значение ячейки, а затем перейти к их удалению. Кажется, что нет быстрого способа удалить строки на основе значения ячейки, но с использованием кода VBA. Вот несколько простых приемов, которые могут вам помочь.
- Удалите строки на основе одного значения ячейки с помощью функции поиска и замены
- Удалить строки на основе одного значения ячейки с кодом VBA
- Удалять строки на основе одного или двух значений ячеек
- Удаление строк на основе нескольких значений ячеек
Удалите строки на основе значения ячейки с помощью функции поиска и замены
В Excel вы можете применить мощную функцию «Найти и заменить», чтобы легко удалять строки на основе определенного значения ячейки. Пожалуйста, сделайте следующее:
1. Выберите диапазон, в котором вы будете удалять строки на основе определенного значения ячейки, и откройте диалоговое окно «Найти и заменить», нажав кнопку Ctrl + F ключи одновременно.
2. В диалоговом окне «Найти и заменить» введите определенное значение ячейки (в нашем случае мы вводим Soe) в Find what и нажмите Find All кнопка. См. Первый снимок экрана ниже:
3. Выберите все результаты поиска в нижней части диалогового окна «Найти и заменить» и закройте это диалоговое окно. (Внимание: Вы можете выбрать один из результатов поиска, а затем Ctrl + A клавиши для выбора всех найденных результатов. См. Второй снимок экрана выше.)
И тогда вы можете увидеть, что все ячейки, содержащие определенное значение, выбраны.
4. Щелкните правой кнопкой мыши выбранные ячейки и выберите Delete из контекстного меню. А затем проверьте Entire row во всплывающем диалоговом окне Удалить и щелкните OK кнопка. Теперь вы увидите, что все ячейки, содержащие определенное значение, удалены. Смотрите скриншоты ниже:
А затем были удалены целые строки на основе уже определенного значения.
Удалить строки на основе значения ячейки с кодом VBA
С помощью следующего кода VBA вы можете быстро удалить строки с определенным значением ячейки, выполните следующие действия:
1, нажмите Alt + F11 ключи одновременно, чтобы открыть Microsoft Visual Basic for applications окно,
2. Нажмите Insert > Module, и введите в модуль следующий код:
VBA: удалить целые строки на основе значения ячейки
Sub DeleteRows()
'Updateby20211217
Dim rng As Range
Dim InputRng As Range
Dim DeleteRng As Range
Dim DeleteStr As String
Dim xTitleId As String
Dim xArr
Dim xF As Integer
Dim xWSh As Worksheet
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set rng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, rng.Address, Type:=8)
If InputRng Is Nothing Then Exit Sub
DeleteStr = Application.InputBox("Delete Text", xTitleId, Type:=2)
Set xWSh = InputRng.Worksheet
For Each rng In InputRng
If rng.Value = DeleteStr Then
If DeleteRng Is Nothing Then
Set DeleteRng = rng
Else
Set DeleteRng = Application.Union(DeleteRng, rng)
Set DeleteRng = DeleteRng.EntireRow
End If
End If
Next
xArr = Split(DeleteRng.AddressLocal, ",")
DeleteRng.Select
DeleteRng.Delete
For xF = UBound(xArr) To 0 Step -1
Set DeleteRng = xWSh.Range(xArr(xF))
DeleteRng.Delete
Next
End Sub
3, Затем нажмите Run кнопку для запуска кода.
4. Во всплывающем диалоговом окне выберите диапазон, в котором вы будете удалять строки на основе определенного значения, и нажмите кнопку OK кнопку.
5. В другом диалоговом окне введите определенное значение, на основе которого вы будете удалять строки, и нажмите кнопку OK кнопка. Смотрите скриншот:
И тогда вы увидите, что целые строки были удалены на основе уже указанного значения.
Удалить строки на основе одного или двух значений ячейки с помощью Kutools for Excel
Если вы установили Kutools for Excel, Его Select Specific Cells Функция может помочь вам быстро удалить строки с определенным значением. Пожалуйста, сделайте следующее:
Kutools for Excel — Включает более 300 удобных инструментов для Excel. Полнофункциональная бесплатная пробная версия 30-день, кредитная карта не требуется! Get It Now
1. Выберите диапазон, в котором вы будете удалять строки на основе определенного значения, и нажмите Kutools > Select > Select Specific Cells. Смотрите скриншот:
2. В открывшемся диалоговом окне Select Specified Cells установите флажок Entire row выберите, выберите Contains от Specific type раскрывающийся список, введите указанное значение в правое поле и щелкните значок Ok кнопку (см. снимок экрана выше).
После применения этой функции появится диалоговое окно, в котором будет показано, сколько ячеек было найдено в соответствии с указанными критериями. Пожалуйста, нажмите на OK чтобы закрыть его.
3. Теперь выбираются целые строки с определенным значением. Щелкните правой кнопкой мыши выбранные строки и щелкните значок Delete из контекстного меню. Смотрите скриншот ниже:
Внимание: Это Select Specific Cells функция поддерживает удаление строк на одно или два определенных значения. Для удаления строк на основе двух указанных значений укажите другое значение в поле Specific type раздел диалогового окна Select Specific Cells, как показано на следующем снимке экрана:
Kutools for Excel — Включает более 300 удобных инструментов для Excel. Полнофункциональная бесплатная пробная версия 30-день, кредитная карта не требуется! Get It Now
Удалить строки на основе нескольких значений ячеек с помощью Kutools for Excel
В некоторых случаях вам может потребоваться удалить строки на основе нескольких значений ячеек из другого столбца / списка в Excel. Здесь я представлю Kutools for Excel‘s Select Same & Different Cells функция, чтобы быстро и легко решить эту проблему.
Kutools for Excel — Включает более 300 удобных инструментов для Excel. Полнофункциональная бесплатная пробная версия 30-день, кредитная карта не требуется! Get It Now
1. Нажмите Kutools > Select > Select Same & Different Cells , чтобы открыть диалоговое окно Выбрать одинаковые и разные ячейки.
2. В открытии Select Same & Different Cells диалоговое окно, сделайте следующее (см. снимок экрана):
(1) В Find values in поле, выберите столбец, в котором вы найдете определенные значения;
(2) В According to поле, выберите столбец / список с несколькими значениями, на основе которых вы будете удалять строки;
(3) В Based on раздел, пожалуйста, проверьте Each row вариант;
(4) В Find раздел, пожалуйста, проверьте Same Values вариант;
(5) Проверьте Select entire rows опция внизу открывающегося диалогового окна.
Внимание: Если два указанных столбца содержат один и тот же заголовок, проверьте My data has headers опцию.
3, Нажмите Ok кнопку, чтобы применить эту утилиту. Затем появляется диалоговое окно, в котором показано, сколько строк было выбрано. Просто нажмите на OK чтобы закрыть его.
Затем были выбраны все строки, содержащие значения из указанного списка.
4. Нажмите Home > Delete > Delete Sheet Rows для удаления всех выбранных строк.
Демо: удаление строк на основе одного или нескольких значений ячеек в Excel
Лучшие инструменты для работы в офисе
Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%
- Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
- Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон…
- Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны…
- Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
- Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
- Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии…
- Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
- Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF…
- Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.
Вкладка Office: интерфейс с вкладками в Office и упрощение работы
- Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
- Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
- Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
In this VBA Tutorial, you learn how to use Excel VBA to delete rows based on a variety of criteria.
This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.
Use the following Table of Contents to navigate to the section you’re interested in.
Related VBA and Macro Tutorials
The following VBA and Macro Tutorials may help you better understand and implement the contents below.
- General VBA constructs and structures:
- Learn about using variables here.
- Learn about VBA data types here.
- Learn about R1C1 style-references here.
- Learn about using worksheet functions in VBA here.
- Practical VBA applications and macro examples:
- Learn how to work with worksheets here.
- Learn how to insert rows here.
- Learn how to delete columns here.
- Learn how to find the last column in a worksheet here.
You can find additional VBA and Macro Tutorials in the Archives.
VBA Code to Delete a Row
To delete a row using VBA, use a statement with the following structure:
Worksheets.Rows(Row#).Delete
Process Followed by VBA Code
VBA Statement Explanation
Worksheets.Rows(Row#).Delete
- Item: Worksheets.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Rows(Row#).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing row number Row# of the worksheet returned by item #1 above.
If you explicitly declare a variable to represent Row#, use the Long data type.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #2 above.
Macro Example
The following macro deletes row 6 of the worksheet named “Delete row”.
Sub deleteRow() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Worksheets("Delete row").Rows(6).Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes row 6 of the worksheet.
#2: Delete a Row and Shift Up
VBA Code to Delete a Row and Shift Up
To delete a row and explicitly shift cells up to replace the deleted row, use a statement with the following structure:
Worksheet.Rows(Row#).Delete Shift:=xlShiftUp
Process Followed by VBA Code
VBA Statement Explanation
Worksheet.Rows(Row#).Delete Shift:=xlShiftUp
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Rows(Row#).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing row number Row# of the worksheet returned by item #1 above.
If you explicitly declare a variable to represent Row#, use the Long data type.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #2 above.
- Item: Shift:=xlShiftUp.
- VBA Construct: Shift parameter of the Range.Delete method.
- Description:
- Shifts rows up (xlShiftUp) to replace the deleted row.
- You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When deleting a row, this generally results in Excel shifting the cells up.
Macro Example
The following macro deletes row 10 of the worksheet named “Delete row” and explicitly specifies to shift cells up to replace the deleted row.
Sub deleteRowShiftUp() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Worksheets("Delete row").Rows(10).Delete Shift:=xlShiftUp End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes row 10 of the worksheet and shifts cells up to replace the deleted row.
#3: Delete Multiple Rows
VBA Code to Delete Multiple Rows
To delete multiple rows, use a statement with the following structure:
Worksheet.Rows("FirstRow#:LastRow#").Delete
Process Followed by VBA Code
VBA Statement Explanation
Worksheet.Rows(“FirstRow#:LastRow#”).Delete
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Rows(“FirstRow#:LastRow#”).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing rows number FirstRow# through LastRow# of the worksheet returned by item #1 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #2 above.
Macro Example
The following macro deletes rows 14 to 18 of the worksheet named “Delete row”.
Sub deleteMultipleRows() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Worksheets("Delete row").Rows("14:18").Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes rows 14 to 18 of the worksheet.
#4: Delete Selected Row
VBA Code to Delete Selected Row
To delete the selected row (the row containing the active cell), use the following statement:
ActiveCell.EntireRow.Delete
Process Followed by VBA Code
VBA Statement Explanation
ActiveCell.EntireRow.Delete
- Item: ActiveCell.
- VBA Construct: Application.ActiveCell property.
- Description: Returns a Range object representing the active cell.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire row containing the cell range returned by item #1 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #2 above.
Macro Example
The following macro deletes the selected row (the row containing the active cell):
Sub deleteSelectedRow() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ ActiveCell.EntireRow.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. When I execute the macro, the active cell is B20. As expected, Excel deletes the selected row.
#5: Delete Multiple Selected Rows
VBA Code to Delete Multiple Selected Rows
To delete multiple selected rows, use the following statement:
Selection.EntireRow.Delete
Process Followed by VBA Code
VBA Statement Explanation
Selection.EntireRow.Delete
- Item: Selection.
- VBA Construct: Application.Selection property.
- Description: Returns a Range object representing the current cell range selection.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire row containing the Range object returned by item #1 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #2 above.
Macro Example
The following macro deletes the (multiple) selected rows.
Sub deleteSelectedRows() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Selection.EntireRow.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. When I execute the macro, the selected cells are B24 to B28. As expected, Excel deletes the selected rows.
#6: Delete Blank Rows
VBA Code to Delete Blank Rows
To delete blank rows, use a macro with the following statement structure:
With Worksheet For Counter = LastRow To FirstRow Step -1 If WorksheetFunction.CountA(.Rows(Counter)) = 0 Then If Not BlankRows Is Nothing Then Set BlankRows = Union(BlankRows, .Rows(Counter)) Else Set BlankRows = .Rows(Counter) End If End If Next Counter End With If Not BlankRows Is Nothing Then BlankRows.Delete
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #11: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #2 through #10 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Lines #2 and #10: For Counter = LastRow To FirstRow Step -1 | Next Counter
- Item: For… Next Counter.
- VBA Construct: For… Next statement.
- Description: Repeats the statements within the loop (lines #3 through #9 below) for each row between (and including) FirstRow (item #4 below) and LastRow (item #3 below).
- Item: Counter.
- VBA Construct: Counter of For… Next statement.
- Description: Loop counter. If you explicitly declare a variable to represent the loop counter, use the Long data type.
- Item: LastRow.
- VBA Construct: Counter Start of For… Next statement.
- Description: Number of the last row (further down the worksheet) you want the macro to consider when identifying blank rows. The number of the last row is also the initial value of Counter (item #2 above).
If you explicitly declare a variable to represent the number of the last row to consider, use the Long data type.
- Item: FirstRow.
- VBA Construct: Counter End of For… Next statement.
- Description: Number of the first row (closer to the top of the worksheet) you want the macro to consider when identifying blank rows. The number of the first row is also the final value of Counter (item (#2 above).
If you explicitly declare a variable to represent the number of the first row to consider, use the Long data type.
- Item: Step -1.
- VBA Construct: Step of For… Next statement.
- Description: Amount by which Counter (item #2 above) changes every time a loop iteration occurs.
In this scenario, you loop backwards: from LastRow (item #3 above) to FirstRow (item #4 above). Therefore, step is -1.
Line #3: If WorksheetFunction.CountA(.Rows(Counter)) = 0 Then
- Item: If… Then.
- VBA Construct: Opening line of If… Then… Else statement.
- Description: Conditionally executes the statements within the If… Then block (lines #4 through #8 below) if the condition specified by item #4 below is met.
- Item: WorksheetFunction.CountA.
- VBA Construct: WorksheetFunction.CountA method.
- Description: Counts the number of cells that aren’t empty in the range returned by item #3 below.
Since the range returned by item #3 below represents the row through which the macro is currently looping, Worksheet.CountA counts the number of cells that aren’t empty in that row.
- Item: .Rows(Counter).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing the row through which the macro is currently looping.
- Item: WorksheetFunction.CountA(.Rows(Counter)) = 0.
- VBA Construct: Condition of If… Then… Else statement.
- Description: This condition is a numeric expression that evaluates to True or False, as follows:
- True: When the WorksheetFunction.CountA method (item #2 above) returns 0. This happens when the row through which the macro is currently looping (item #3 above) is empty and, therefore, the number of non-empty cells is 0.
- False: When WorksheetFunction.CountA returns a number other than 0. This happens when the row through which the macro is currently looping isn’t empty and, therefore, the number of non-empty cells isn’t 0.
Line #4: If Not BlankRows Is Nothing Then
- Item: If… Then.
- VBA Construct: Opening line of If… Then… Else statement.
- Description: Conditionally executes the statement within the If… Then… Else block (line #5 below) if the condition specified by item #6 below is met.
- Item: Not.
- VBA Construct: Not operator.
- Description: Carries out a logical negation on item #3 below. In other words, if item #3 returns:
- True, the result is False.
- False, the result is True.
- Item: BlankRows.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the empty rows found by the macro.
- Item: Is.
- VBA Construct: Is Operator.
- Description: Compares 2 object reference variables: (i) Not BlankRows (items #2 and #3 above) vs. (ii) Nothing (item #5 below).
If both object references refer to the same object, the Is operator returns True. If they refer to different objects, Is returns False.
- Item: Nothing.
- Description: The default value for a data type. In the case of an object variable (such as BlankRows), a null reference.
- Item: Not BlankRows Is Nothing.
- VBA Construct: Condition of If… Then… Else statement.
- Description: The condition is an expression that evaluates to True or False, as follows:
- True: When “Not BlankRows” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when BlankRows is “something”.
Since BlankRows holds a Range object representing cell ranges within the empty rows found by the macro, BlankRows is something if the macro finds at least one such row.
- False: When “Not BlankRows” refers to a different object from Nothing. This happens when BlankRows itself is Nothing. This occurs prior to the macro finding the first empty row. This is because BlankRows isn’t assigned to anything prior to that moment.
- True: When “Not BlankRows” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when BlankRows is “something”.
Line #5: Set BlankRows = Union(BlankRows, .Rows(Counter))
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by item #6 below to BlankRows (item #2 below).
- Item: BlankRows.
- VBA Construct: Object (Range) variable of Set statement.
- Description:
- Holds a Range object representing the empty rows found by the macro.
- BlankRows is included twice in the statement. In the first mention (Set BlankRows), BlankRows is the object variable to which an object reference is assigned.
- Item: Union.
- VBA Construct: Application.Union method.
- Description: Returns a Range object representing the union of the Range objects returned by items #4 and #5 below.
- Item: BlankRows.
- VBA Construct: Object (Range) variable.
- Description:
- Holds a Range object representing the empty rows found by the macro.
- BlankRows is included twice in the statement. In the second mention (Union(BlankRows, .Rows(Counter)), BlankRows is one of the parameters of the Application.Union method.
- Item: .Rows(Counter).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing the row through which the macro is currently looping.
- Item: Union(BlankRows, .Rows(Counter).
- VBA Construct: Object expression of Set statement.
- Description: Returns the new Range object reference assigned to the BlankRows object variable (item #2 above). This is the union of the following 2 Range objects:
- Prior to the Set statement, BlankRows represents cell ranges within the empty rows found by the macro prior to the row through which it’s currently looping.
- “.Rows(Counter)” represents the row through which the macro is currently looping.
Graphically, this looks as follows:
In other words, any empty row the macro finds is “added” to BlankRows.
Line #6: Else
- Item: Else.
- VBA Construct: Else clause of If… Then… Else statement.
- Description: The statement following the Else clause (line #7 below) is executed if the condition tested in the opening line of the If… Then… Else statement (line #4 above) isn’t met and returns False.
Line #7: Set BlankRows = .Rows(Counter)
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by item #3 below to BlankRows (item #2 below).
- Item: BlankRows.
- VBA Construct: Object (Range) variable of Set statement.
- Description: Holds a Range object representing the empty rows found by the macro.
- Item: .Rows(Counter).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing the row through which the macro is currently looping.
Lines #8 and #9: End If | End If
- Item: End If.
- VBA Construct: Closing lines of If… Then… Else statements.
- Description: Ends the If… Then… Else statements that began in lines #3 and #4 above.
Line #12: If Not BlankRows Is Nothing Then BlankRows.Delete
- Item: If… Then.
- VBA Construct: If… Then… Else statement.
- Description: Conditionally executes the statement at the end of the line (items #7 and #8 below) if the condition specified by item #6 below is met.
- Item: Not.
- VBA Construct: Not operator.
- Description: Carries out a logical negation on item #3 below. In other words, if item #3 returns:
- True, the result is False.
- False, the result is True.
- Item: BlankRows.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the empty rows found by the macro.
- Item: Is.
- VBA Construct: Is Operator.
- Description: Compares 2 object reference variables: (i) Not BlankRows (items #2 and #3 above) vs. (ii) Nothing (item #5 below).
If both object references refer to the same object, the Is operator returns True. If they refer to different objects, Is returns False.
- Item: Nothing.
- Description: The default value for a data type. In the case of an object variable (such as BlankRows), a null reference.
- Item: Not BlankRows Is Nothing.
- VBA Construct: Condition of If… Then… Else statement.
- Description: The condition is an expression that evaluates to True or False, as follows:
- True: When “Not BlankRows” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when BlankRows is “something”.
Since BlankRows holds a Range object representing cell ranges within the empty rows found by the macro, BlankRows is something if the macro has found at least 1 empty row.
- False: When “Not BlankRows” refers to a different object from Nothing. This happens when BlankRows itself is Nothing. This, in turn, occurs when the macro founds no empty rows.
- True: When “Not BlankRows” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when BlankRows is “something”.
- Item: BlankRows.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the empty rows found by the macro.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #7 above.
Macro Example
The following macro deletes all blank rows between rows number myFirstRow and LastRow.
- myFirstRow is set to 6.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete empty rows”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
Sub deleteEmptyRows() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myWorksheet As Worksheet Dim iCounter As Long Dim myBlankRows As Range myFirstRow = 6 Set myWorksheet = Worksheets("Delete empty rows") With myWorksheet myLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row For iCounter = myLastRow To myFirstRow Step -1 If WorksheetFunction.CountA(.Rows(iCounter)) = 0 Then If Not myBlankRows Is Nothing Then Set myBlankRows = Union(myBlankRows, .Rows(iCounter)) Else Set myBlankRows = .Rows(iCounter) End If End If Next iCounter End With If Not myBlankRows Is Nothing Then myBlankRows.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes all blank rows between row 6 and the last row with data on the worksheet.
#7: Delete Rows with Blank Cells
VBA Code to Delete Rows with Blank Cells
To delete rows with blank cells using VBA, use a macro with the following statement structure:
With Worksheet Set RangeForCriteria = .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) End With On Error Resume Next RangeForCriteria.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #3: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: The statement within the With… End With statement (line #2 below) is executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Line #2: Set RangeForCriteria = .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn))
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by items #3 through #5 below to RangeForCriteria (item #2 below).
- Item: RangeForCriteria.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cell range you want the macro to search for blank cells.
- Item: .Range.
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell range specified as follows:
- Upper-left corner cell: Range object returned by item #4 below.
- Lower-right corner cell: Range object returned by item #5 below.
- Item: .Cells(FirstRow, FirstColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number FirstRow and column number FirstColumn.
FirstRow and FirstColumn are the number of, respectively, the first row and first column in the cell range you want the macro to search for blank cells. If you explicitly declare a variable to represent FirstRow or FirstColumn, use the Long data type.
- Item: .Cells(LastRow, LastColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number LastRow and column number LastColumn.
LastRow and LastColumn are the number of, respectively, the last row and last column in the cell range you want the macro to search for blank cells. If you explicitly declare a variable to represent LastRow or LastColumn, use the Long data type.
Line #4: On Error Resume Next
- Item: On Error Resume Next.
- VBA Construct: On Error Resume Next statement.
- Description: Specifies that, when a run-time error occurs, control goes to the statement following the statement where the error occurs.
The error-handler in this line #4 is necessary because, if the cell range you want the macro to search for blank cells doesn’t contain any such cells, line #5 below generates a run-time error.
Line #5: RangeForCriteria.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
- Item: RangeForCriteria.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cell range you want the macro to search for blank cells.
- Item: SpecialCells(xlCellTypeBlanks).
- VBA Construct: Range.SpecialCells method and Type parameter of Range.SpecialCells method.
- Description: Returns a Range object representing all empty cells within the cell range returned by RangeForCriteria (item #1 above).
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire rows containing the Range object returned by item #2 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #3 above.
Macro Example
The following macro deletes all rows with blank cells between:
- Rows number myFirstRow and myLastRow.
- Columns number myFirstColumn and myLastColumn.
In this example:
- myFirstRow is set to 6.
- myFirstColumn is set to 2.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete row with blank cells”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
- myLastColumn is set to the number of the last column with data in the same worksheet. The constructs used by the statement that finds the last column with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Column property.
Sub deleteRowBlankCells() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long Dim myWorksheet As Worksheet Dim myRange As Range myFirstRow = 6 myFirstColumn = 2 Set myWorksheet = Worksheets("Delete row with blank cells") With myWorksheet With .Cells myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End With Set myRange = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) End With On Error Resume Next myRange.SpecialCells(xlCellTypeBlanks).EntireRow.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes all rows with blank cells between (i) row 6 and the last row with data on the worksheet, and (ii) column 2 and the last column with data on the worksheet.
#8: Delete Rows with Blank Cells in a Specific Column
VBA Code to Delete Rows with Blank Cells in a Specific Column
To delete rows with blank cells in a specific column using VBA, use a macro with the following statement structure:
With Worksheet With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) .AutoFilter Field:=CriteriaField, Criteria1:="=" On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #8: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #2 through #7 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Lines #2 and #6: With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #3 through #6 below) are executed on the range object returned by items #2 through #4 below.
- Item: .Range.
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell range specified as follows:
- Upper-left corner cell: Range object returned by item #3 below.
- Lower-right corner cell: Range object returned by item #4 below.
- Item: .Cells(FirstRow, FirstColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number FirstRow and column number FirstColumn.
FirstRow and FirstColumn are the number of, respectively, the first row and first column in the cell range you work with. If you explicitly declare a variable to represent FirstRow or FirstColumn, use the Long data type.
- Item: .Cells(LastRow, LastColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number LastRow and column number LastColumn.
LastRow and LastColumn are the number of, respectively, the last row and last column in the cell range you work with. If you explicitly declare a variable to represent LastRow or LastColumn, use the Long data type.
Line #3: .AutoFilter Field:=CriteriaField, Criteria1:=”=”
- Item: .AutoFilter.
- VBA Construct: Range.AutoFilter method.
- Description: Filter the data within the range you work with using the AutoFilter and according to the parameters specified by items #2 and #3 below.
- Item: Field:=CriteriaField.
- VBA Construct: Field parameter of Range.AutoFilter method.
- Description: Specifies the field on which you want to base the filter. The leftmost field of the range you work with is Field 1. The rightmost field is the number of fields in the cell range you work with.
If you explicitly declare a variable to represent CriteriaField, use the Long data type.
- Item: Criteria1:=”=”.
- VBA Construct: Criteria1 parameter of Range.AutoFilter method.
- Description: Specifies the filtering criteria. “=” finds blank cells.
Line #4: On Error Resume Next
- Item: On Error Resume Next.
- VBA Construct: On Error Resume Next statement.
- Description: Specifies that, when a run-time error occurs, control goes to the statement following the statement where the error occurs.
The error-handler in this line #4 is necessary because, if the field you filter by (line #3 above) doesn’t contain blank cells, line #5 below generates a run-time error.
Line #5: .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count – 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete
- Item: Offset.
- VBA Construct: Range.Offset property.
- Description: Returns a Range object a number of rows above or below the cell range it works with, as returned by line #2 above.
- Item: RowOffset:=1.
- VBA Construct: RowOffset parameter of Range.Offset property.
- Description: Specifies that the cell range returned by Range.Offset (item #1 above) is 1 row below the range specified in line #2 above.
Line #2 above specifies the cell range you work with. Therefore, the Range object that Range.Offset returns has the same size but is 1 row below the cell range you work with. This results in the following:
- The headers of the cell range you work with are excluded from the Range object.
- The first empty row below the last row with data (LastRow in line #2 above) is included. This extra line is handled by item #7 below.
- Item: Resize.
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above.
- Item: RowSize.
- VBA Construct: RowSize parameter of Range.Resize property.
- Description: Specifies the number of rows in the new cell range returned by Range.Resize (item #3 above).
- Item: Rows.
- VBA Construct: Range.Rows property.
- Description: Returns a Range object representing the rows in the cell range it works with, as returned by line #2 above.
- Item: Count.
- VBA Construct: Range.Count property.
- Description: Returns the number of rows within the Range object returned by item #5 above.
- Item: Resize(RowSize:=(.Rows.Count – 1)).
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above to reduce it by one row. The number of rows in the new range is obtained by subtracting 1 from the number of rows returned by line #2, as counted by items #5 and #6 above.
This results in a cell range that excludes the first empty row below the last row with data that the Range.Offset property (items #1 and #2 above) included.
- Item: SpecialCells(xlCellTypeVisible).
- VBA Construct: Range.SpecialCells method and Type parameter of Range.SpecialCells method.
- Description: Returns a Range object representing all visible cells within the cell range you work with, excluding the headers (as required by item #2 above).
Since line #3 above filters the data according to the criteria you specify, the visible cells returned by Range.SpecialCells are those containing blank cells in the column (field) you specify.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire rows containing the Range object returned by item #8 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #10 above.
Line #7: .AutoFilterMode = False
- Item: .AutoFilterMode = False.
- VBA Construct: Worksheet.AutoFilterMode property.
- Description: Specifies that the AutoFilter drop-down arrows aren’t displayed on the worksheet.
Macro Example
The following macro deletes all rows that meet the following conditions:
- Are between:
- Rows number (myFirstRow + 1) and myLastrow.
- Columns number myFirstColumn and myLastColumn.
- Contain a blank cell in field number myCriteriaField.
In this example:
- myFirstRow is set to 5.
- myFirstColumn is set to 2.
- myCriteriaField is set to 1.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete row if cell is blank”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
- myLastColumn is set to the number of the last column with data in the same worksheet. The constructs used by the statement that finds the last column with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Column property.
Sub deleteRowBlankCell() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long Dim myCriteriaField As Long Dim myWorksheet As Worksheet myFirstRow = 5 myFirstColumn = 2 myCriteriaField = 1 Set myWorksheet = Worksheets("Delete row if cell is blank") With myWorksheet With .Cells myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End With With .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) .AutoFilter Field:=myCriteriaField, Criteria1:="=" On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes the rows containing blank cells in myCriteriaField (1).
#9: Delete Rows Containing Strings
VBA Code to Delete Rows Containing Strings
To delete rows containing strings using VBA, use a macro with the following statement structure:
With Worksheet Set RangeForCriteria = .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) End With On Error Resume Next RangeForCriteria.SpecialCells(xlCellTypeConstants, xlTextValues).EntireRow.Delete
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #3: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: The statement within the With… End With statement (line #2 below) is executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Line #2: Set RangeForCriteria = .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn))
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by items #3 through #5 below to RangeForCriteria (item #2 below).
- Item: RangeForCriteria.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cell range you want the macro to search for cells containing strings.
- Item: .Range.
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell range specified as follows:
- Upper-left corner cell: Range object returned by item #4 below.
- Lower-right corner cell: Range object returned by item #5 below.
- Item: .Cells(FirstRow, FirstColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number FirstRow and column number FirstColumn.
FirstRow and FirstColumn are the number of, respectively, the first row and first column in the cell range you want the macro to search for cells containing strings. If you explicitly declare a variable to represent FirstRow or FirstColumn, use the Long data type.
- Item: .Cells(LastRow, LastColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number LastRow and column number LastColumn.
LastRow and LastColumn are the number of, respectively, the last row and last column in the cell range you want the macro to search for cells containing strings. If you explicitly declare a variable to represent LastRow or LastColumn, use the Long data type.
Line #4: On Error Resume Next
- Item: On Error Resume Next.
- VBA Construct: On Error Resume Next statement.
- Description: Specifies that, when a run-time error occurs, control goes to the statement following the statement where the error occurs.
The error-handler in this line #4 is necessary because, if the cell range you want the macro to search for cells containing strings doesn’t contain any such cells, line #5 below generates a run-time error.
Line #5: RangeForCriteria.SpecialCells(xlCellTypeConstants, xlTextValues).EntireRow.Delete
- Item: RangeForCriteria.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cell range you want the macro to search for cells containing strings.
- Item: SpecialCells(xlCellTypeConstants, xlTextValues).
- VBA Construct: Range.SpecialCells method, Type and Value parameters of Range.SpecialCells method.
- Description: Returns a Range object representing all cells containing constant (xlCellTypeConstants) text values (xlTextValues) within the cell range returned by RangeForCriteria (item #1 above). Those are the cells containing strings.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire rows containing the Range object returned by item #2 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #3 above.
Macro Example
The following macro deletes all rows containing strings between:
- Rows number myFirstRow and myLastRow.
- Columns number myFirstColumn and myLastColumn.
In this example:
- myFirstRow is set to 6.
- myFirstColumn is set to 2.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete rows containing strings”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
- myLastColumn is set to the number of the last column with data in the same worksheet. The constructs used by the statement that finds the last column with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Column property.
Sub deleteRowContainingStrings() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long Dim myWorksheet As Worksheet Dim myRange As Range myFirstRow = 6 myFirstColumn = 2 Set myWorksheet = Worksheets("Delete rows containing strings") With myWorksheet With .Cells myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End With Set myRange = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) End With On Error Resume Next myRange.SpecialCells(xlCellTypeConstants, xlTextValues).EntireRow.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes all rows containing strings between (i) row 6 and the last row with data on the worksheet, and (ii) column 2 and the last column with data on the worksheet.
#10: Delete Row Based on Cell Value
VBA Code to Delete Row Based on Cell Value
To delete rows based on the value in a specific cell using VBA, use a macro with the following statement structure:
With Worksheet With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) .AutoFilter Field:=CriteriaField, Criteria1:=Value On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #8: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #2 through #7 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Lines #2 and #6: With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #3 through #6 below) are executed on the range object returned by items #2 through #4 below.
- Item: .Range.
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell range specified as follows:
- Upper-left corner cell: Range object returned by item #3 below.
- Lower-right corner cell: Range object returned by item #4 below.
- Item: .Cells(FirstRow, FirstColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number FirstRow and column number FirstColumn.
FirstRow and FirstColumn are the number of, respectively, the first row and first column in the cell range you work with. If you explicitly declare a variable to represent FirstRow or FirstColumn, use the Long data type.
- Item: .Cells(LastRow, LastColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number LastRow and column number LastColumn.
LastRow and LastColumn are the number of, respectively, the last row and last column in the cell range you work with. If you explicitly declare a variable to represent LastRow or LastColumn, use the Long data type.
Line #3: .AutoFilter Field:=CriteriaField, Criteria1:=Value
- Item: .AutoFilter.
- VBA Construct: Range.AutoFilter method.
- Description: Filter the data within the range you work with using the AutoFilter and according to the parameters specified by items #2 and #3 below.
- Item: Field:=CriteriaField.
- VBA Construct: Field parameter of Range.AutoFilter method.
- Description: Specifies the field on which you want to base the filter. The leftmost field of the range you work with is Field 1. The rightmost field is the number of fields in the cell range you work with.
If you explicitly declare a variable to represent CriteriaField, use the Long data type.
- Item: Criteria1:=Value.
- VBA Construct: Criteria1 parameter of Range.AutoFilter method.
- Description: Specifies the filtering criteria. If you explicitly declare a variable to represent Value, ensure that the data type you use can handle the value you use as criteria.
Line #4: On Error Resume Next
- Item: On Error Resume Next.
- VBA Construct: On Error Resume Next statement.
- Description: Specifies that, when a run-time error occurs, control goes to the statement following the statement where the error occurs.
The error-handler in this line #4 is necessary because, if the field you filter by (line #3 above) doesn’t contain cells with the value you use as criteria, line #5 below generates a run-time error.
Line #5: .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count – 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete
- Item: Offset.
- VBA Construct: Range.Offset property.
- Description: Returns a Range object a number of rows above or below the cell range it works with, as returned by line #2 above.
- Item: RowOffset:=1.
- VBA Construct: RowOffset parameter of Range.Offset property.
- Description: Specifies that the cell range returned by Range.Offset (item #1 above) is 1 row below the range specified in line #2 above.
Line #2 above specifies the cell range you work with. Therefore, the Range object that Range.Offset returns has the same size but is 1 row below the cell range you work with. This results in the following:
- The headers of the cell range you work with are excluded from the Range object.
- The first empty row below the last row with data (LastRow in line #2 above) is included. This extra line is handled by item #7 below.
- Item: Resize.
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above.
- Item: RowSize.
- VBA Construct: RowSize parameter of Range.Resize property.
- Description: Specifies the number of rows in the new cell range returned by Range.Resize (item #3 above).
- Item: Rows.
- VBA Construct: Range.Rows property.
- Description: Returns a Range object representing the rows in the cell range it works with, as returned by line #2 above.
- Item: Count.
- VBA Construct: Range.Count property.
- Description: Returns the number of rows within the Range object returned by item #5 above.
- Item: Resize(RowSize:=(.Rows.Count – 1)).
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above to reduce it by one row. The number of rows in the new range is obtained by subtracting 1 from the number of rows returned by line #2, as counted by items #5 and #6 above.
This results in a cell range that excludes the first empty row below the last row with data that the Range.Offset property (items #1 and #2 above) included.
- Item: SpecialCells(xlCellTypeVisible).
- VBA Construct: Range.SpecialCells method and Type parameter of Range.SpecialCells method.
- Description: Returns a Range object representing all visible cells within the cell range you work with, excluding the headers (as required by item #2 above).
Since line #3 above filters the data according to the criteria you specify, the visible cells returned by Range.SpecialCells are those containing the value you’re looking for in the column (field) you specify.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire rows containing the Range object returned by item #8 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #10 above.
Line #7: .AutoFilterMode = False
- Item: .AutoFilterMode = False.
- VBA Construct: Worksheet.AutoFilterMode property.
- Description: Specifies that the AutoFilter drop-down arrows aren’t displayed on the worksheet.
Macro Example
The following macro deletes all rows that meet the following conditions:
- Are between:
- Rows number (myFirstRow + 1) and myLastRow.
- Columns number myFirstColumn and myLastColumn.
- Contain the value myValue in field number myCriteriaField.
In this example:
- myFirstRow is set to 5.
- myFirstColumn is set to 2.
- myCriteriaField is set to 1.
- myValue is set to 5.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete row based on value”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
- myLastColumn is set to the number of the last column with data in the same worksheet. The constructs used by the statement that finds the last column with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Column property.
Sub deleteRowBasedOnValue() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long Dim myCriteriaField As Long Dim myValue As Double Dim myWorksheet As Worksheet myFirstRow = 5 myFirstColumn = 2 myCriteriaField = 1 myValue = 5 Set myWorksheet = Worksheets("Delete row based on value") With myWorksheet With .Cells myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End With With .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) .AutoFilter Field:=myCriteriaField, Criteria1:=myValue On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes the rows containing myValue (5) in myCriteriaField (1).
#11: Delete Row Based on Date
VBA Code to Delete Row Based on Date
To delete rows based on the date in a specific cell using VBA, use a macro with the following statement structure:
With Worksheet For Counter = LastRow To FirstRow Step -1 With .Cells(Counter, CriteriaColumn) If .Value = Date Then If Not RowsWithDate Is Nothing Then Set RowsWithDate = Union(RowsWithDate, .Cells) Else Set RowsWithDate = .Cells End If End If End With Next Counter End With If Not RowsWithDate Is Nothing Then RowsWithDate.EntireRow.Delete
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #13: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #2 through #12 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Lines #2 and #12: For Counter = LastRow To FirstRow Step -1 | Next Counter
- Item: For… Next Counter.
- VBA Construct: For… Next statement.
- Description: Repeats the statements within the loop (lines #3 through #11 below) for each row between (and including FirstRow (item #4 below) and LastRow (item #3 below).
- Item: Counter.
- VBA Construct: Counter of For… Next statement.
- Description: Loop counter. If you explicitly declare a variable to represent the loop counter, use the Long data type.
- Item: LastRow.
- VBA Construct: Counter Start of For… Next statement.
- Description: Number of the last row (further down the worksheet) you want the macro to consider when identifying blank rows. The number of the last row is also the initial value of Counter (item #2 above).
If you explicitly declare a variable to represent the number of the last row to consider, use the Long data type.
- Item: FirstRow.
- VBA Construct: Counter End of For… Next statement.
- Description: Number of the first row (closer to the top of the worksheet) you want the macro to consider when identifying blank rows. The number of the first row is also the final value of Counter (item (#2 above).
If you explicitly declare a variable to represent the number of the first row to consider, use the Long data type.
- Item: Step -1.
- VBA Construct: Step of For… Next statement.
- Description: Amount by which Counter (item #2 above) changes every time a loop iteration occurs.
In this scenario, you loop backwards: from LastRow (item #3 above) to FirstRow (item #4 above). Therefore, step is -1.
Lines #3 and #11: With .Cells(Counter, CriteriaColumn) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #4 through #10 below) are executed on the cell returned by item #2 below.
- Item: .Cells(Counter, CriteriaColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number Counter and column number CriteriaColumn.
At any given time, the value of the loop counter (Counter) is the same as that of the row through which the macro is currently looping. CriteriaColumn is the number of the column containing the cells with dates you consider.
Line #4: If .Value = Date Then
- Item: If… Then.
- VBA Construct: Opening line of If… Then… Else statement.
- Description: Conditionally executes the statements within the If… Then block (lines #5 through #9 below) if the condition specified by item #3 below is met.
- Item: .Value.
- VBA Construct: Range.Value property.
- Description: Returns the value of the cell represented by the Range object returned by line #3 above (.Cells(Counter, CriteriaColumn)). This is the value of the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider.
- Item: .Value = Date.
- VBA Construct: Condition of If… Then… Else statement.
- Description: This condition is a numeric expression that evaluates to True or False, as follows:
- True: When the value of the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider is equal to the date you specify (Date).
- False: When the value of the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider isn’t equal to the date you specify (Date).
If you explicitly declare a variable to represent Date, ensure that the data type you use can handle the value you use as criteria. Consider, for example, using the Date data type.
When specifying the date you use as criteria, ensure that you specify the date as a value as required by VBA. For these purposes, you can use VBA constructs such as the DateValue or DateSerial Functions.
Line #5: If Not RowsWithDate Is Nothing Then
- Item: If… Then.
- VBA Construct: Opening line of If… Then… Else statement.
- Description: Conditionally executes the statement within the If… Then… Else block (line #6 below) if the condition specified by item #6 below is met.
- Item: Not.
- VBA Construct: Not operator.
- Description: Carries out a logical negation on item #3 below. In other words, if item #3 returns:
- True, the result is False.
- False, the result is True.
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- Item: Is.
- VBA Construct: Is Operator.
- Description: Compares 2 object reference variables: (i) Not RowsWithDate (items #2 and #3 above) vs. (ii) Nothing (item #5 below).
If both object references refer to the same object, the Is operator returns True. If they refer to different objects, Is returns False.
- Item: Nothing.
- Description: The default value for a data type. In the case of an object variable (such as RowsWithDate), a null reference.
- Item: Not RowsWithDate Is Nothing.
- VBA Construct: Condition of If… Then… Else statement.
- Description: The condition is an expression that evaluates to True or False, as follows:
- True: When “Not RowsWithDate” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when RowsWithDate is “something”.
Since RowsWithDate holds a Range object representing the cells with the criteria date found by the macro in a specific column (CriteriaColumn in line #3 above), RowsWithDate is something after the macro finds the first such cell.
- False: When “Not RowsWithDate” refers to a different object from Nothing. This happens when RowsWithDate itself is Nothing. This occurs prior to the macro finding the first cell with the criteria date. This is because RowsWithDate isn’t assigned to anything prior to that moment.
- True: When “Not RowsWithDate” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when RowsWithDate is “something”.
Line #6: Set RowsWithDate = Union(RowsWithDate, .Cells)
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by item #6 below to RowsWithDate (item #2 below).
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable of Set statement.
- Description:
- Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- RowsWithDate is included twice in the statement. In the first mention (Set RowsWithDate), RowsWithDate is the object variable to which an object reference is assigned.
- Item: Union.
- VBA Construct: Application.Union method.
- Description: Returns a Range object representing the union of the Range objects returned by items #4 and #5 below.
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable.
- Description:
- Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- RowsWithDate is included twice in the statement. In the second mention (Union(RowsWithDate, .Cells), RowsWithDate is one of the parameters of the Application.Union method.
- Item: .Cells.
- VBA Construct: Range.Cells property.
- Description: Returns a Range object representing the cell represented by the Range object returned by line #3 above (.Cells(Counter, CriteriaColumn)). This is the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider.
- Item: Union(RowsWithDate, .Cells).
- VBA Construct: Object expression of Set statement.
- Description: Returns the new Range object reference assigned to the RowsWithDate object variable (item #2 above). This is the union of the following 2 Range objects:
- Prior to the Set statement, RowsWithDate represents cells in the column you specify containing the date you use as criteria found by the macro prior to the row through which it’s currently looping.
- “.Cells” represents the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider.
Graphically, this looks as follows:
In other words, any cell containing the criteria date the macro finds is “added” to RowsWithDate.
Line #7: Else
- Item: Else.
- VBA Construct: Else clause of If… Then… Else statement.
- Description: The statement following the Else clause (line #8 below) is executed if the condition tested in the opening line of the If… Then… Else statement (line #5 above) isn’t met and returns False.
Line #8: Set RowsWithDate = .Cells
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by item #3 below to RowsWithDate (item #2 below).
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable of Set statement.
- Description: Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- Item: .Cells.
- VBA Construct: Range.Cells property.
- Description: Returns a Range object representing the cell represented by the Range object returned by line #3 above (.Cells(Counter, CriteriaColumn)). This is the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider.
Lines #9 and #10: End If | End If
- Item: End If.
- VBA Construct: Closing lines of If… Then… Else statements.
- Description: Ends the If… Then… Else statements that began in lines #4 and #5 above.
Line #14: If Not RowsWithDate Is Nothing Then RowsWithDate.EntireRow.Delete
- Item: If… Then.
- VBA Construct: If… Then… Else statement.
- Description: Conditionally executes the statement within at the end of the line (items #7 through #9 below) if the condition specified by item #6 below is met.
- Item: Not.
- VBA Construct: Not operator.
- Description: Carries out a logical negation on item #3 below. In other words, if item #3 returns:
- True, the result is False.
- False, the result is True.
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- Item: Is.
- VBA Construct: Is Operator.
- Description: Compares 2 object reference variables: (i) Not RowsWithDate (items #2 and #3 above) vs. (ii) Nothing (item #5 below).
If both object references refer to the same object, the Is operator returns True. If they refer to different objects, Is returns False.
- Item: Nothing.
- Description: The default value for a data type. In the case of an object variable (such as RowsWithDate), a null reference.
- Item: Not RowsWithDate Is Nothing.
- VBA Construct: Condition of If… Then… Else statement.
- Description: The condition is an expression that evaluates to True or False, as follows:
- True: When “Not RowsWithDate” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when RowsWithDate is “something”.
Since RowsWithDate holds a Range object representing the cells with the criteria date found by the macro in a specific column (CriteriaColumn in line #3 above), RowsWithDate is something if the macro finds at least one such cell.
- False: When “Not RowsWithDate” refers to a different object from Nothing. This happens when RowsWithDate itself is Nothing. This, in turn, occurs when the macro founds no cells with the criteria date within the specified column.
- True: When “Not RowsWithDate” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when RowsWithDate is “something”.
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire row containing the cell range returned by item #7 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #8 above.
Macro Example
The following macro deletes all rows that meet the following conditions:
- Are between rows number myFirstRow and myLastRow.
- Contain the date myDate in column number myCriteriaColumn.
In this example:
- myFirstRow is set to 5.
- myDate is set to the serial number representing June 15, 2017. For purposes of obtaining the appropriate serial number, I use the DateValue Function.
- myCriteriaColumn is set to 2.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete row based on date”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
Sub deleteRowBasedOnDate() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myCriteriaColumn As Long Dim myDate As Date Dim myWorksheet As Worksheet Dim iCounter As Long Dim myRowsWithDate As Range myFirstRow = 6 myCriteriaColumn = 2 myDate = DateValue("June 15, 2017") Set myWorksheet = Worksheets("Delete row based on date") With myWorksheet myLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row For iCounter = myLastRow To myFirstRow Step -1 With .Cells(iCounter, myCriteriaColumn) If .Value = myDate Then If Not myRowsWithDate Is Nothing Then Set myRowsWithDate = Union(myRowsWithDate, .Cells) Else Set myRowsWithDate = .Cells End If End If End With Next iCounter End With If Not myRowsWithDate Is Nothing Then myRowsWithDate.EntireRow.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes the rows containing myDate (June 15, 2017) in myCriteriaColumn (2).
#12: Delete Row Based on String Criteria
VBA Code to Delete Row Based on String Criteria
To delete rows based on the string in a specific cell using VBA, use a macro with the following statement structure:
With Worksheet With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) .AutoFilter Field:=CriteriaField, Criteria1:=String On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #8: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #2 through #7 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Lines #2 and #6: With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #3 through #6 below) are executed on the range object returned by items #2 through #4 below.
- Item: .Range.
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell range specified as follows:
- Upper-left corner cell: Range object returned by item #3 below.
- Lower-right corner cell: Range object returned by item #4 below.
- Item: .Cells(FirstRow, FirstColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number FirstRow and column number FirstColumn.
FirstRow and FirstColumn are the number of, respectively, the first row and first column in the cell range you work with. If you explicitly declare a variable to represent FirstRow or FirstColumn, use the Long data type.
- Item: .Cells(LastRow, LastColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number LastRow and column number LastColumn.
LastRow and LastColumn are the number of, respectively, the last row and last column in the cell range you work with. If you explicitly declare a variable to represent LastRow or LastColumn, use the Long data type.
Line #3: .AutoFilter Field:=CriteriaField, Criteria1:=String
- Item: .AutoFilter.
- VBA Construct: Range.AutoFilter method.
- Description: Filter the data within the range you work with using the AutoFilter and according to the parameters specified by items #2 and #3 below.
- Item: Field:=CriteriaField.
- VBA Construct: Field parameter of Range.AutoFilter method.
- Description: Specifies the field on which you want to base the filter. The leftmost field of the range you work with is Field 1. The rightmost field is the number of fields in the cell range you work with.
If you explicitly declare a variable to represent CriteriaField, use the Long data type.
- Item: Criteria1:=String.
- VBA Construct: Criteria1 parameter of Range.AutoFilter method.
- Description: Specifies the filtering criteria. If you explicitly declare a variable to represent String, use the String data type.
Line #4: On Error Resume Next
- Item: On Error Resume Next.
- VBA Construct: On Error Resume Next statement.
- Description: Specifies that, when a run-time error occurs, control goes to the statement following the statement where the error occurs.
The error-handler in this line #4 is necessary because, if the field you filter by (line #3 above) doesn’t contain cells with the string you use as criteria, line #5 below generates a run-time error.
Line #5: .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count – 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete
- Item: Offset.
- VBA Construct: Range.Offset property.
- Description: Returns a Range object a number of rows above or below the cell range it works with, as returned by line #2 above.
- Item: RowOffset:=1.
- VBA Construct: RowOffset parameter of Range.Offset property.
- Description: Specifies that the cell range returned by Range.Offset (item #1 above) is 1 row below the range specified in line #2 above.
Line #2 above specifies the cell range you work with. Therefore, the Range object that Range.Offset returns has the same size but is 1 row below the cell range you work with. This results in the following:
- The headers of the cell range you work with are excluded from the Range object.
- The first empty row below the last row with data (LastRow in line #2 above) is included. This extra line is handled by item #7 below.
- Item: Resize.
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above.
- Item: RowSize.
- VBA Construct: RowSize parameter of Range.Resize property.
- Description: Specifies the number of rows in the new cell range returned by Range.Resize (item #3 above).
- Item: Rows.
- VBA Construct: Range.Rows property.
- Description: Returns a Range object representing the rows in the cell range it works with, as returned by line #2 above.
- Item: Count.
- VBA Construct: Range.Count property.
- Description: Returns the number of rows within the Range object returned by item #5 above.
- Item: Resize(RowSize:=(.Rows.Count – 1)).
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above to reduce it by one row. The number of rows in the new range is obtained by subtracting 1 from the number of rows returned by line #2, as counted by items #5 and #6 above.
This results in a cell range that excludes the first empty row below the last row with data that the Range.Offset property (items #1 and #2 above) included.
- Item: SpecialCells(xlCellTypeVisible).
- VBA Construct: Range.SpecialCells method and Type parameter of Range.SpecialCells method.
- Description: Returns a Range object representing all visible cells within the cell range you work with, excluding the headers (as required by item #2 above).
Since line #3 above filters the data according to the criteria you specify, the visible cells returned by Range.SpecialCells are those containing the string you’re looking for in the column (field) you specify.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire rows containing the Range object returned by item #8 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #10 above.
Line #7: .AutoFilterMode = False
- Item: .AutoFilterMode = False.
- VBA Construct: Worksheet.AutoFilterMode property.
- Description: Specifies that the AutoFilter drop-down arrows aren’t displayed on the worksheet.
Macro Example
The following macro deletes all rows that meet the following conditions:
- Are between:
- Rows number (myFirstRow + 1) and myLastRow.
- Columns number myFirstColumn and myLastColumn.
- Contain the string myString in field number myCriteriaField.
In this example:
- myFirstRow is set to 5.
- myFirstColumn is set to 2.
- myCriteriaField is set to 1.
- myString is set to “*to delete*”.
The asterisks at the beginning and end of the string act as wildcards representing any number of characters. Therefore, myString includes any strings that contain “to delete”, regardless of the text before or after it.
For example, in the example below, I use this macro to delete rows where the cell in the first column contains the string “Rows to delete now”. “to delete” is between the strings “Rows ” and ” now”, both of which are covered by the asterisk wildcard.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete row based on string”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
- myLastColumn is set to the number of the last column with data in the same worksheet. The constructs used by the statement that finds the last column with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Column property.
Sub deleteRowBasedOnString() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long Dim myCriteriaField As Long Dim myString As String Dim myWorksheet As Worksheet myFirstRow = 5 myFirstColumn = 2 myCriteriaField = 1 myString = "*to delete*" Set myWorksheet = Worksheets("Delete row based on string") With myWorksheet With .Cells myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End With With .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) .AutoFilter Field:=myCriteriaField, Criteria1:=myString On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes the rows containing myString (“*to delete*”) in myCriteriaField (1).
References to VBA Constructs Used in this VBA Tutorial
Use the following links to visit the appropriate webpage within the Microsoft Office Dev Center:
- Identify the worksheet you work with:
- Workbook.Worksheets property.
- Find last row and last column with data in a worksheet and count number of rows in a cell range:
- Range.Find method.
- Range.Count property.
- Return Range objects:
- Application.ActiveCell property.
- Worksheet.Cells property.
- Range.Cells property.
- Range.Offset property.
- Range.Resize property.
- Application.Union method.
- Return Range objects representing rows:
- Worksheet.Rows property.
- Range.Rows property.
- Range.EntireRow property.
- Loop through rows:
- For… Next statement.
- Specify criteria for row deletion:
- DateSerial Function.
- DateValue Function.
- Range.Value property.
- Test if (i) rows meet criteria for deletion, or (ii) the macro has found rows or cells meeting the criteria for deletion:
- If… Then… Else statement.
- Range.AutoFilter method.
- Range.SpecialCells method.
- WorksheetFunction.CountA method.
- Not operator.
- Is operator.
- Delete rows.
- Range.Delete method.
- Work with variables:
- Dim statement.
- Set statement.
- Data types:
- Data data type.
- Double data type.
- Long data type.
- Object data type.
- String data type.
- Variant data type.
- Simplify object references:
- With… End With statement.
- Handle errors:
- On Error statement.
- Remove AutoFilter drop-down arrows:
- Worksheet.AutoFilterMode property.