Vba excel быстрое удаление строк

 

Djinn

Пользователь

Сообщений: 69
Регистрация: 30.05.2016

Всем добрый вечер. Возник вопрос, каким способом можно наиболее быстро удалить строки в примере во вложении. Необходимо удалить все строки с минимальной датой. Дело в том в реальности строк в файле под миллион, циклы и фильтры очень тяжело работают.

 

Ts.Soft

Пользователь

Сообщений: 576
Регистрация: 13.04.2016

Как вариант — отсортировать по дате, прогнать цикл до первой даты большей минимально, удалить строки с первой до найденной минус одна.
Если сортировка неприемлема и последовательность важна, то сначала в свободную колонку записать текущий номер строки, потом выполнить вышеперечисленные действия и отсортировать по столбцу куда записывались номера строк.

Не стреляйте в тапера — он играет как может.

 

БМВ

Модератор

Сообщений: 21378
Регистрация: 28.12.2016

Excel 2013, 2016

#3

04.10.2018 23:10:52

Цитата
Ts.Soft написал:
и последовательность важна, то сначала в свободную колонку

поставить метку. Отсортировать по этому столбцу,  выделить диапазон с меткой и удалить. Остальные строки останутся в прежней сортировке и без ненужных строк.

Изменено: БМВ04.10.2018 23:11:55

По вопросам из тем форума, личку не читаю.

 

_Igor_61

Пользователь

Сообщений: 3007
Регистрация: 18.07.2016

#4

04.10.2018 23:16:43

Может, так попробовать?

Код
Sub Stroki()
   ThisWorkbook.Worksheets("Лист1").Activate
   Dim i As Long
   Dim lr As Long
   Dim R As Long
   Dim NR As Long
   Dim a
   i = Evaluate("MIN(A:A)")
   lr = Worksheets("Лист1").Cells(Rows.Count, 1).End(xlUp).Row
   a = Worksheets("Лист1").Range("A2:A" & lr) 'если нужно больше столбцов в массиве - добавьте
   ReDim b(1 To UBound(a), 1 To 1)            'с первого по первый столбец (добавьте, если нужно больше)
   For R = 1 To UBound(a)
   If a(R, 1) <> i Then
       NR = NR + 1
       b(NR, 1) = a(R, 1)
       End If
   Next R
       Worksheets("Лист1").Range("A2:A" & lr).ClearContents
       Worksheets("Лист1").Range("A2").Resize(NR) = b
End Sub

p.s. Если столбцов не очень много, то зачем удалять полностью строки

Изменено: _Igor_6104.10.2018 23:34:12

 

ocet p

Пользователь

Сообщений: 438
Регистрация: 24.03.2018

#5

05.10.2018 01:30:50

Код, аналогичный коду _Igor_61, попробуйте:

Код
Option Explicit

Sub bez_min_daty()
Dim r&, c%, i&, j%, k&, min_date, tbl_tmp(), tbl()
Dim tmr!: tmr = Timer

    With Application
        .ScreenUpdating = False: .DisplayAlerts = False
        .EnableEvents = False: .Calculation = xlManual
    End With
    
    With Range("a1").CurrentRegion
        r = .Rows.Count - 1: c = .Columns.Count
        min_date = Application.Min(.Offset(1, 0).Resize(r, 1))
        tbl_tmp = .Offset(1, 0).Resize(r, c).Value
    End With
    
    For i = 1 To r
        If tbl_tmp(i, 1) <> min_date Then k = k + 1
    Next
    
    ReDim tbl(1 To k, 1 To c): k = 0
    
    For i = 1 To r
        If tbl_tmp(i, 1) <> min_date Then
            k = k + 1
            For j = 1 To c
                tbl(k, j) = tbl_tmp(i, j)
            Next
        End If
    Next
    
    Erase tbl_tmp
    
    With Range("a1").CurrentRegion.Offset(1, 0)
        .Resize(r, c).Clear: .Resize(k, c).Value = tbl
    End With
    
    Erase tbl
    
    With Application
        .Calculation = xlAutomatic: .EnableEvents = True
        .DisplayAlerts = True: .ScreenUpdating = True
    End With
    
    MsgBox "Ves' protsess prodolzhalsya: " & CStr(Round(Timer - tmr, 4)) & " s", vbOKOnly, "Info !"
End Sub

Изменено: ocet p05.10.2018 01:32:26

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

Был быстрый код от ZVI (через сортировку). Найду — выложу. Или буду у ПК — выложу слегка доработанный.

«Бритва Оккама» или «Принцип Калашникова»?

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#7

05.10.2018 20:44:27

Вот нашел от ZVI

Код
==============================================================
Мне необходимо удалить строки со нулевыми значиниями из Листа, но там порядка 200 000 строк.
ZVI 
Процедура очистки(удаления) строк в столбце ColNum со значениями DelValue: 
'===================================================================================
' Sub         : DelRows(TableHeader,ColNum,DelValue)
' TableHeader : Range; table header range
' ColNum      : Long; column number with DelValue
' DelValue    : Variant; value of rows to be deleted
'-------------+---------------------------------------------------------------------
' VBA call    : DelRows ActiveSheet.Range("A1:H1"), 5, 0
'-------------+---------------------------------------------------------------------
' Created     : ZVI:2009:12:26 [url]http://www.sql.ru/forum/actualthread.aspx?tid=722758[/url]
'-----------------------------------------------------------------------------------
Sub DelRows(TableHeader As Range, ColNum As Long, DelValue)
  Dim Arr(), r&, rs&, cs&, i&, v, ac
  With TableHeader.CurrentRegion
    rs = .Rows.Count - TableHeader.Row + .Row
    cs = .Columns.Count - TableHeader.Column + .Column
  End With
  With TableHeader.Resize(rs, 1)
    Arr() = .Offset(, cs).Value
    ' Check DelValue
    For Each v In .Offset(, ColNum - 1).Value
      r = r + 1
      If v <> DelValue Then
        i = i + 1
        Arr(r, 1) = 1
      End If
    Next
    If i < rs Then
      ' Freeze on
      With Application
        .ScreenUpdating = False
        .EnableEvents = False
        ac = .Calculation: .Calculation = xlCalculationManual
      End With
      ' Delete rows with DelValue in ColNum
      .Offset(, cs) = Arr
      .Resize(, cs + 1).Sort .Cells(1).Offset(, cs), 1, Header:=xlNo
      .Resize(, 1).Offset(, cs).ClearContents
      .Resize(rs - i, cs).Offset(i).Clear   ' или .Resize(rs - i).Offset(i).EntireRow.Delete
      ' Freeze off
      With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = ac
      End With
    End If
  End With
End Sub
 
 
Тестирование:
 
Sub Test()
  DelRows ActiveSheet.Range("A1:H1"), 5, 0
End Sub

Отсюда

.

«Бритва Оккама» или «Принцип Калашникова»?

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

Допилиливал код, когда не требуется доп. столбец. Если будет нужно выложу.

«Бритва Оккама» или «Принцип Калашникова»?

 

Александр Усков

Пользователь

Сообщений: 2
Регистрация: 15.06.2022

#9

15.06.2022 09:00:41

Цитата
написал:
Допилиливал код, когда не требуется доп. столбец. Если будет нужно выложу.

Можно посмотреть код, без доп. столбца?
Понимаю, что прошло уже 4ре года…

 

Jack Famous

Пользователь

Сообщений: 10848
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

RAN, судя по Return, это не VBA  :)
Ну а так наиболее высокая скорость будет только при удалении одного сплошного диапазона, что возможно только при сортировке.
Все остальные варианты можно ускорить за счёт

нарезания строки адресов для укрупнения диапазонов

и

быстрого получения буквы столбца по его номеру

(для получения адреса)

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#12

15.06.2022 10:18:39

Цитата
Jack Famous написал:
судя по Return, это не VBA  

в VBA тоже есть return.

Цитата
Александр Усков написал:
Можно посмотреть код

если найду, скину. Там весь смысл в том, что сортируем сразу по ключевому столбцу, первоначально правильно его подготовив/заполнив.

Изменено: bedvit15.06.2022 10:21:03

«Бритва Оккама» или «Принцип Калашникова»?

 

Jack Famous

Пользователь

Сообщений: 10848
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#13

15.06.2022 10:29:11

Цитата
bedvit: смысл в том, что сортируем сразу по ключевому столбцу, первоначально правильно его подготовив/заполнив

прикольно, кстати!  :idea: Можно приклеить слева индексы в виде «!000123» (или заменить значения всех ячеек удаляемых строк на «!!! $%$ !!!» например) для сортировки и всё готово. Отличная идея!

Цитата
bedvit: в VBA тоже есть return

как использовать и для чего нужен?

Так

вызывает ошибку

Цитата
Jack Famous: наиболее высокая скорость будет только при удалении одного сплошного диапазона

если задача позволяет, то можно собрать новый массив без «удаляемых» строк и выгрузить в старый или другое место — это ещё быстрее

Изменено: Jack Famous15.06.2022 10:35:28

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#14

15.06.2022 10:42:59

Цитата
Jack Famous написал:
судя по Return, это не VBA
Код
GoSub sRange
 

Jack Famous

Пользователь

Сообщений: 10848
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#15

15.06.2022 11:07:03

RAN, не заметил)) теперь я понимаю, какой переход по меткам не любят — вот такой  :D
Какой смысл скакать в конец и потом возвращаться, если это просто ветка If…Then?…
Простите за оффотоп и докопательство — я хоть сам и люблю метки, но вот тут не понимаю, правда  :)

Было и стало

Изменено: Jack Famous15.06.2022 11:09:32

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#16

15.06.2022 13:36:24

Цитата
Jack Famous написал:
это просто ветка If…Then?

Это не так.
GoSub — как вариант — это замена функции — не нужно передавать параметры и не нужны глобальные переменные.

Пример здесь
И здесь

Думаю есть и другие применения GoSub , но я пользуюсь именно этими функционалом.

«Бритва Оккама» или «Принцип Калашникова»?

 

Jack Famous

Пользователь

Сообщений: 10848
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#17

15.06.2022 13:44:47

Цитата
bedvit: Это не так

это ТАК.
Если можно заменить обычной веткой, то зачем:
    1. перескакивать в конец процедуры
    2. Возвращаться обратно
    3. Не забыть выйти из процедуры перед блоком GoSub

В применении меток я руководствуюсь тем, что без них код был бы больше, ветвистее и/или запутаннее.
Применяю обычно для перехода к следующему элементу цикла, выхода из множества вложенных циклов, прыжка назад (например при необходимости повторного ввода пользователем, пока не введёт правильно) или прыжка в конец, чтобы отобразить общее для множества ситуаций сообщения и/или «включения» обратно всех Application (нужно и в случае аварийного выхода и при штатной работе).

Кому как удобно конечно, но я для GoSub пока у себя нигде применения не вижу, а в этом конкретном случае показал, как безболезненно он заменяется на обычное ветвление.

Изменено: Jack Famous15.06.2022 13:45:42

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#18

15.06.2022 14:17:15

Цитата
Александр Усков написал:
Можно посмотреть код, без доп. столбца?

Нашел отрывки, скомпилировал в целый

Код
Sub DelRows_20220615() ' - для форума, без доп. поля
Dim rStart, rEnd, cStart, cEnd, keyColumn, Rng, arr(), arr2(), v, r, key, i
        
keyColumn = 1 'задаем ключевой столбец, по которому проверяем условия для удаления строк
key = 4 'задаём ключ по которому будем отбирать в ключевом столбце значения

With ActiveSheet.UsedRange 'определим границы диапазона по на активном листе
    rStart = .Row: rEnd = .Row + .Rows.count - 1  'задаем  границы диапазона строк
    cStart = .Column:  cEnd = .Column + .Columns.count - 1 'задаем  границы диапазона столбцов
End With

Set Rng = Range(Cells(rStart, 1), Cells(rEnd, cEnd)) 'берем с 1го, что бы не запутаться с keyColumn 
arr() = Rng.Resize(, 1).Offset(, keyColumn - 1).Value 'ключевой столбец
arr2() = arr 'ключевой столбец - копия

With Rng
    For r = 1 To .Rows.count
        v = arr(r, 1)
        If Not IsError(v) Then If v = key Then i = i + 1: arr2(i, 1) = arr(r, 1): arr(r, 1) = i Else arr(r, 1) = ""
    Next

    If i < .Rows.count And i Then 'если найдены нужные данные и их меньше чем исходный диапазон
        .Resize(, 1).Offset(, keyColumn - 1).Value = arr() 'ключ для сортировки
        .Sort .Resize(, 1).Offset(, keyColumn - 1), 1, Header:=xlNo 'данные без заголовка
        .Resize(i, 1).Offset(, keyColumn - 1).Value = arr2() 'ключ изначальный только по нужным
        .Resize(.Rows.count - i).Offset(i).Delete Shift:=xlUp  'удаляем остаток
    End If
End With
    
End Sub

Изменено: bedvit15.06.2022 14:40:26

«Бритва Оккама» или «Принцип Калашникова»?

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#19

15.06.2022 14:20:44

Jack Famous, замени в моем коде так же безболезненно

Цитата
Jack Famous написал:
обычной веткой

Вот

пример

(высылал ранее первой ссылкой)

Изменено: bedvit15.06.2022 14:21:22

«Бритва Оккама» или «Принцип Калашникова»?

 

AlSeUs

Пользователь

Сообщений: 2
Регистрация: 15.06.2022

#20

15.06.2022 14:33:32

Цитата
написал:
Нашел отрывки, скомпилировал в целый

Огромное спасибо!

 

Jack Famous

Пользователь

Сообщений: 10848
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#21

15.06.2022 14:38:36

Цитата
bedvit: замени в моем коде так же безболезненно

я не говорил, что везде можно заменить веткой — опять ты выдумываешь, фантазёр  :D
У тебя 2 обращения и тут уже альтернатива только процедура — с параметрами (много) или глобальными общими переменными. У тебя это ещё хоть как-то уместно (хотя в моём SmartUnion‘е я обошёлся без таких сложностей)

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#22

15.06.2022 14:46:56

Цитата
Jack Famous написал:
опять ты выдумываешь, фантазёр

Где я выдумывал хоть раз? Укажи.

Если ты говоришь, про конкретный случай, то я его не смотрел, возможно код можно оптимизировать (мой ответ был не про этот случай, а про GoSub (+Return))

Если мы говорим про GoSub (+Return) и про то,

Цитата
Jack Famous написал:
как использовать и для чего нужен?

Я тебе ответил, где используют и для каких случаев он нужен.

Изменено: bedvit15.06.2022 14:48:02

«Бритва Оккама» или «Принцип Калашникова»?

 

Jack Famous

Пользователь

Сообщений: 10848
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#23

15.06.2022 15:52:34

Цитата
bedvit: Я тебе ответил, где используют и для каких случаев он нужен
Цитата
bedvit: GoSub — как вариант — это замена функции — не нужно передавать параметры и не нужны глобальные переменные

спасибо  :idea:

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#24

15.06.2022 16:00:43

Цитата
Jack Famous написал:
Если можно заменить обычной веткой, то зачем

Не помню, почему в этом случае моей левой задней ноге захотелось написать именно так.

Цитата
Jack Famous написал:
то зачем:     1. перескакивать в конец процедуры     2. Возвращаться обратно

А зачем выносить фрагмент кода в отдельную процедуру? Выходить из основной, и возвращаться обратно?

Цитата
Jack Famous написал:
Не забыть выйти из процедуры перед блоком GoSub

Это даже не смешно. Не забыть внешнюю процедуру определить как Sub или Fanction.
А то, что ты с наскока не видишь пряники, так бывает…

In this Article

  • Delete Entire Row or Column
    • Delete Multiple Rows or Columns
  • Delete Blank / Empty Rows
    • Delete Row if Cell is Blank
  • Delete Row Based on Cell Value
  • More Delete Row and Column Examples
    • Delete Duplicate Rows
    • Delete Table Rows
    • Delete Filtered Rows
    • Delete Rows in Range
    • Delete Selected Rows
    • Delete Last Row
    • Delete Columns by Number

This tutorial will demonstrate different ways to delete rows and columns in Excel using VBA.

Delete Entire Row or Column

To delete an entire row in VBA use this line of code:

Rows(1).Delete

Notice we use the Delete method to delete a row.

Instead of referencing the Rows Object, you can reference rows based on their Range Object with EntireRow:

Range("a1").EntireRow.Delete

Similarly to delete an entire column, use these lines of code:

Columns(1).Delete
Range("a1").EntireColumn.Delete

Delete Multiple Rows or Columns

Using the same logic, you can also delete multiple rows at once:

Rows("1:3").Delete

or columns:

Columns("A:C").Delete

Notice here we reference the specific row and column numbers / letters surrounded by quotations.

Of course, you can also reference the EntireRow of a range:

Range("a1:a10").EntireRow.Delete

Note: The examples below only demonstrate deleting rows, however as you can see above, the syntax is virtually identically to delete columns.

Delete Blank / Empty Rows

This example will delete a row if the entire row is blank:

Sub DeleteRows_EntireRowBlank()

Dim cell As Range

For Each cell In Range("b2:b20")
    If Application.WorksheetFunction.CountA(cell.EntireRow) = 0 Then
        cell.EntireRow.Delete
    End If
Next cell

End Sub

It makes use of the Excel worksheet function: COUNTA.

Delete Row if Cell is Blank

This will delete a row if specific column in that row is blank (in this case column B):

Range("b3:b20").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

Delete Row Based on Cell Value

This will loop through a range, and delete rows if a certain cell value in that row says “delete”.

Sub DeleteRowswithSpecificValue()

Dim cell As Range

For Each cell In Range("b2:b20")
    If cell.Value = "delete" Then
        cell.EntireRow.Delete
    End If
Next cell

End Sub

More Delete Row and Column Examples

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Delete Duplicate Rows

This code will delete all duplicate rows in a range:

Range("b2:c100").RemoveDuplicates Columns:=2

Notice we set Columns:=2. This tells VBA to check both the first two columns of data when considering if rows are duplicates. A duplicate is only found when both columns have duplicate values.

If we had set this to 1, only the first row would’ve been checked for duplicate values.

Delete Table Rows

This code will delete the second row in a Table by referencing ListObjects.

ThisWorkbook.Sheets("Sheet1").ListObjects("list1").ListRows(2).Delete

Delete Filtered Rows

To delete only rows that are visible after filtering:

Range("b3:b20").SpecialCells(xlCellTypeVisible).EntireRow.Delete

VBA Programming | Code Generator does work for you!

Delete Rows in Range

This code will delete all rows in range:

Range("a1:a10").EntireRow.Delete

Delete Selected Rows

This code will delete all selected rows:

Selection.EntireRow.Delete

Delete Last Row

This will delete the last used row in column B:

Cells(Rows.Count, 2).End(xlUp).EntireRow.Delete

By changing 2 to 1, you can delete the last used row in column A, etc.:

Cells(Rows.Count, 1).End(xlUp).EntireRow.Delete

Delete Columns by Number

To delete a column by it’s number, use a code like this:

Columns (2).Delete

AndreA SN

1014 / 118 / 2

Регистрация: 26.08.2011

Сообщений: 1,113

Записей в блоге: 2

1

Как быстро удалять лишние строки?

27.05.2016, 09:41. Показов 9518. Ответов 29

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

На листе есть структурированные данные: столбцов 40-250 (иногда больше), строк вообще 100 000-140 000 (и очень часто может быть больше).
Я нарисовал функцию, которая выбирает уникальные строки, остальные с листа удаляет командой

Visual Basic
1
 Rows(i).Delete

Работает это крайне медленно. На обработку 140 000 строк (осталось 28861 уникальных) ушло что-то около 6 часов.
Сделать массив и обработать его не представляется возможным: слишком здоровый получается 140 000 строк * 200 столбцов *64 (тип Variant) = 1792 000 000
Вообщем лучше на листе…

Может у кого есть идеи — как это ускорить?
А то на ночь ставлю — и не факт, что утром будет готово…



0



Модератор

Эксперт MS Access

11341 / 4660 / 748

Регистрация: 07.08.2010

Сообщений: 13,496

Записей в блоге: 4

27.05.2016, 09:49

2

удалять надо от последней записи к первой
а как написан ваш макрос



1



Hugo121

6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

27.05.2016, 10:13

3

Для удаления строк есть быстрый код от ZVI — только вот что-то найти не могу…
Идея в том, чтоб проставить единички в массив, выгрузить рядом с данными, отсортировать, удалить сразу всё одним блоком.

Добавлено через 2 минуты
Нашёл:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
==============================================================
Мне необходимо удалить строки со нулевыми значиниями из Листа, но там порядка 200 000 строк.
ZVI 
Процедура очистки(удаления) строк в столбце ColNum со значениями DelValue: 
'===================================================================================
' Sub         : DelRows(TableHeader,ColNum,DelValue)
' TableHeader : Range; table header range
' ColNum      : Long; column number with DelValue
' DelValue    : Variant; value of rows to be deleted
'-------------+---------------------------------------------------------------------
' VBA call    : DelRows ActiveSheet.Range("A1:H1"), 5, 0
'-------------+---------------------------------------------------------------------
' Created     : ZVI:2009:12:26 [url]http://www.sql.ru/forum/actualthread.aspx?tid=722758[/url]
'-----------------------------------------------------------------------------------
Sub DelRows(TableHeader As Range, ColNum As Long, DelValue)
  Dim Arr(), r&, rs&, cs&, i&, v, ac
  With TableHeader.CurrentRegion
    rs = .Rows.Count - TableHeader.Row + .Row
    cs = .Columns.Count - TableHeader.Column + .Column
  End With
  With TableHeader.Resize(rs, 1)
    Arr() = .Offset(, cs).Value
    ' Check DelValue
    For Each v In .Offset(, ColNum - 1).Value
      r = r + 1
      If v <> DelValue Then
        i = i + 1
        Arr(r, 1) = 1
      End If
    Next
    If i < rs Then
      ' Freeze on
      With Application
        .ScreenUpdating = False
        .EnableEvents = False
        ac = .Calculation: .Calculation = xlCalculationManual
      End With
      ' Delete rows with DelValue in ColNum
      .Offset(, cs) = Arr
      .Resize(, cs + 1).Sort .Cells(1).Offset(, cs), 1, Header:=xlNo
      .Resize(, 1).Offset(, cs).ClearContents
      .Resize(rs - i, cs).Offset(i).Clear   ' или .Resize(rs - i).Offset(i).EntireRow.Delete
      ' Freeze off
      With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = ac
      End With
    End If
  End With
End Sub
 
 
Тестирование:
 
Sub Test()
  DelRows ActiveSheet.Range("A1:H1"), 5, 0
End Sub
 
Круто, попробовал на миллионе строк в Excel 2007, работает, причем очень быстро.
==

Добавлено через 9 минут
Кстати там в той оригинальной теме я что-то с словарями писал — может там сразу и удаление неуникальных было, детали естественно не помню…
А не, там задача была «удалить все строки в 7 столбце, значение которых не равно 2 или 3» — но думаю можно приспособить для анализа уникальности. Если конечно под Виндовс работаете.



2



1024 / 227 / 21

Регистрация: 20.05.2016

Сообщений: 971

Записей в блоге: 19

27.05.2016, 10:45

4

НЕ знаю можно ли давать ссылку на сторонние ресурсы (если нельзя — выложу здесь), но аналогичную тему я поднимал здесь. Посмотрите, возможно это решит вашу проблему.



1



4 / 4 / 3

Регистрация: 19.08.2013

Сообщений: 24

27.05.2016, 11:10

5

Hugo121, спасибо за код, сохраню к себе в памятку. вообще когда появляется необходимость в ручную удалить много строк из еще большего количества(до миллиона) я сначала фильтром выделяю то, что хочу удалить, после последнего столбца ставлю везде 1. делаю по нему сортировку и удаляю.



1



1014 / 118 / 2

Регистрация: 26.08.2011

Сообщений: 1,113

Записей в блоге: 2

27.05.2016, 11:30

 [ТС]

6

shanemac51, спасибо за совет. А можно немножко пояснить — почему именно так?
Hugo121, меня немного смутило то, что на SQL -ресурсе опубликовано… но если написано для Excel — то в принципе надо пробовать… Сейчас прога работает — я чуть позже покопаюсь в коде.
Хотя уже сейчас есть вопрос — сортировка… Что обеспечивается командой Sort?
Вообще у меня каждая строка, намеченная на удаление, помечена словом «дубликат». Понимаю. что расточительство. но через время — понимать и код и содержимое листа проще. По идее, есть возможность отфильтровать строки с этой меткой одним движением.
Думаю, лучше будет выделить строки через Union

Добавлено через 2 минуты
mitsakoolt, спасибо… стало понятно зачем сортировка тут… Хотя если несмежные диапазоны выделены — неужели нет способа их удалить без сортировки?



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

27.05.2016, 11:35

7

Через union дольше, но тоже вариант.
Как раз вчера такое делал (вернее гонял ранее написанное) — само объединение делает за пару секунд, но вот затем удаление происходит раз так в 10 дольше.
А если удалять построчно — то нужно снизу вверх потому что каждая удалённая строка как ни странно удаляется
Т.е. пропадает и на её место сдвигается строка снизу, которую возможно тоже нужно бы удалить…



0



1014 / 118 / 2

Регистрация: 26.08.2011

Сообщений: 1,113

Записей в блоге: 2

27.05.2016, 11:39

 [ТС]

8

от жыж блин… А у меня прога работает… щас буду курочить код



0



bedvit

1024 / 227 / 21

Регистрация: 20.05.2016

Сообщений: 971

Записей в блоге: 19

27.05.2016, 11:45

9

Мой не подходит по ссылке? исходник (без правки)

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Sub ВыделитьСтроки() 'выделить/удалить все НЕ пустые строки не содержащие значение "Баранова О.В."
Dim строка As LongPtr
Dim строки As Range
Dim строки2 As Range
 
     For строка = 3000 To 1 Step -1
        If Cells(строка, 1) <> "Баранова О.В." And Cells(строка, 1) <> "" Then Set строки = Rows(строка)
            If строки2 Is Nothing Then Set строки2 = строки Else Set строки2 = Union(строки2, строки)
     Next строка
  
'Debug.Print строки2.Address 'посмотреть диапазоны адресов
If Not строки2 Is Nothing Then строки2.Select 'выделить
'If Not строки2 Is Nothing Then строки2.Delete Shift:=xlUp 'удалить со свигом вверх
End Sub



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

27.05.2016, 11:52

10

bedvit, тоже можно, но для количества в сотни тысяч строк как минимум перебирать и анализировать нужно бы данные массива — тут у Вас на каждую строку идёт два обращения к листу, что в 43*2 раза дольше, чем обращение к массиву.
Да и если всё брать в юнион — то не важно с какого конца перебирать, можно и сверху вниз.



0



1014 / 118 / 2

Регистрация: 26.08.2011

Сообщений: 1,113

Записей в блоге: 2

27.05.2016, 11:59

 [ТС]

11

bedvit, на основе его и буду колупать… и закомментированную строку с delete попытаюсь использовать… только дождусь когда прога доработает …



0



bedvit

1024 / 227 / 21

Регистрация: 20.05.2016

Сообщений: 971

Записей в блоге: 19

27.05.2016, 12:48

12

Hugo121, в общем согласен с вами. Выделение 1 млн. строк с поиском по условию 11 сек., это много, но по сравнению с операцией удаления

Цитата
Сообщение от AndreA SN
Посмотреть сообщение

около 6 часов

, копейки. Плюс Union — медленная функция. Если вам будет интересно здесь максимальной производительности для Union (выделение 250 тыс. несвязных ячеек за 5 сек.)

Добавлено через 23 минуты
Поиск по условию через массив (0,078125 сек.), при отключенном Union. Теперь только вопрос в Union, и самой операции удаления.

Visual Basic
1
2
3
4
5
6
7
8
9
10
Sub ВыделитьСтроки() 'выделить/удалить все НЕ пустые строки не содержащие значение "Баранова О.В."
Dim строка As Long, строки As Range, строки2 As Range, R
R = Range(Cells(1, 1), Cells(Rows.Count, 1).End(xlUp)).Value 'забрать в массив столбец А с первой ячейки до последней заполнненной
     For строка = 1 To UBound(R) 'по последний заполненный
        If R(строка, 1) <> "" And R(строка, 1) <> "Баранова О.В." Then Set строки = Rows(строка)
            If строки2 Is Nothing Then Set строки2 = строки Else Set строки2 = Union(строки2, строки)
     Next строка
If Not строки2 Is Nothing Then строки2.Select 'выделить
'If Not строки2 Is Nothing Then строки2.Delete Shift:=xlUp 'удалить со свигом вверх
End Sub

Добавлено через 4 минуты
С двумя условиями 0,16796875 сек.



0



Hugo121

6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

27.05.2016, 12:49

13

Visual Basic
1
If R(строка, 1) <> "" And R(строка, 1) <> "Баранова О.В." Then

тут можно ускорить, если сделать цепочку If-Then — ведь нет смысла проверять Баранове, если там пусто, а сейчас проверяется!



0



mitsakoolt

4 / 4 / 3

Регистрация: 19.08.2013

Сообщений: 24

27.05.2016, 12:53

14

Цитата
Сообщение от AndreA SN
Посмотреть сообщение

Хотя если несмежные диапазоны выделены — неужели нет способа их удалить без сортировки?

удалить можно, но процесс будет очень долгим. я первый раз с вечера поставил удалять, утром вернулся и удаление еще продолжалось. тогда было около 700 000 строк, из них почти половину нужно было удалить. и диапазоны в среднем были по 1-3 строки. при сортировке когда удаляешь одним диапазоном все происходит за секунды. хотя через макрос наверно будет также и без сортировке если ввести

Visual Basic
1
2
3
4
With Application
.ScreenUpdating = False
 .Calculation = xlManual
 End With

надо потестировать



0



1024 / 227 / 21

Регистрация: 20.05.2016

Сообщений: 971

Записей в блоге: 19

27.05.2016, 13:04

15

Но Union нужен, когда строки нельзя сортировать, когда их много и когда их нужно удалить разом (что быстрее чем по одной или по несколько за раз)

Добавлено через 4 минуты
Hugo121, согласен. Можно да же удалить второе условие, ТС возможно нужно только одно условие.
думаю отключение экрана и перерасчет сильно не поможет в моем коде, там и так разом все делается (удаление).

Добавлено через 3 минуты
Каждое условие это 0,08 сек., копейки-копеек по сравнению с другими расчетами)



0



Модератор

Эксперт MS Access

11341 / 4660 / 748

Регистрация: 07.08.2010

Сообщений: 13,496

Записей в блоге: 4

27.05.2016, 14:30

16

Цитата
Сообщение от AndreA SN
Посмотреть сообщение

слишком здоровый получается 140 000 строк * 200 столбцов *64 (тип Variant) = 1792 000 000

а что скажете про форматирование и формулы
насколько сложно



0



AndreA SN

1014 / 118 / 2

Регистрация: 26.08.2011

Сообщений: 1,113

Записей в блоге: 2

28.05.2016, 15:16

 [ТС]

17

Ребята. Очень извиняюсь… Сейчас готовлюсь исчезнуть дней на 40… Поэтому работаю с Вашими рекомендациями очень нерегулярно… и отвечаю тоже… Тренируюсь на левшу. Экстренно))) Ибо чую — очень надо это мне на лето.

Галина. Форматирование и формулы в массив не гружу. Гружу командой

Visual Basic
1
mass = Range(Cells(1, 1), Cells(row_, col_)).Value

При выгрузке из массива ничего не считаю. Лист получает только числа в текстовом режиме и текст. Если и идет время на форматирование, то форматирует числа Excel сам — автоматически.

Добавлено через 1 минуту
Выгружаю из массива уже обработанные данные аналогично
Собственно здесь потери времени минимальны

Добавлено через 1 час 1 минуту
Вот что у меня получилось

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
idcolprb = 19 ' перед работой этого кода в 19 колонке делаю пометки дубликатов
 
' ST - проверяемая в данную итерацию строка
' ST2 - собираемый на удаление диапазон срок
 
 Dim ST As Range, ST2 As Range
 i = 2
    Do
        If Cells(i, idcolprb).Value = Empty Then Exit Do
        If Cells(i, idcolprb).Value = "дубликат" Then
            Set ST = Rows(i)
            If ST2 Is Nothing Then Set ST2 = ST Else Set ST2 = Union(ST2, ST)
        End If
        i = i + 1
     Loop
If Not ST2 Is Nothing Then 
    ST2.Select 'ВЫДЕЛИТЬ все отобранные строки
    ST2.Delete Shift:=xlUp 'удалить выделенные строки со сдвигом вверх
end if

Спасибо Вам за помощь



0



shanemac51

Модератор

Эксперт MS Access

11341 / 4660 / 748

Регистрация: 07.08.2010

Сообщений: 13,496

Записей в блоге: 4

28.05.2016, 17:11

18

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Dim ws As Worksheet
Dim j1 As Long, j2 As Long, j3, dt
 
 
With Application
.ScreenUpdating = False
 .Calculation = xlManual
 End With
Set ws = Excel.Worksheets("zrab")
'' заполнение 150000 строк, 150 столбцов
'ws.Range("b2:ee150000") = "wwwwjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj"
dt = Timer
j1 = 150000
j2 = 0
j3 = 0
Do While j1 > 0
j2 = j2 + 1
j3 = j3 + 1
 
If j2 = 5 Then  '''каждую 5-ю
ws.Rows(j1).Delete
j2 = 0
If j3 > 1000 Then   '''''трассер
Debug.Print j1; (Timer - dt)  1
j3 = 0
End If
 
 
 
End If
j1 = j1 - 1
Loop
Debug.Print Now
MsgBox "выполнение в секундах(около 4мин)=" & (Timer - dt)  1



1



Hugo121

6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

28.05.2016, 23:38

19

Я думаю быстрее будет в union брать не всю строку, а только одну ячейку строки.
А в конце удалять

Visual Basic
1
ST2.EntireRow.Delete

как выше в коде ZVI



1



1024 / 227 / 21

Регистрация: 20.05.2016

Сообщений: 971

Записей в блоге: 19

29.05.2016, 18:36

20

Hugo121, хорошая идея. Сегодня протестировал немного. Если строк много (на удаление) несколько десятков тысяч, Union работает медленно и удаление не столь быстрое как хотелось.
AndreA SN, сортировка в условиях задачи разрешается? Формул, условного форматирование нет? Порядок следования строк сохранятся должен?



0



First, let me say categorically that there is nothing wrong with loops — they certainly have their place!

Recently we were presented with the below situation:

400000  |  Smith, John| 2.4   | 5.66|   =C1+D1
400001  |  Q, Suzy    | 4.6   | 5.47|   =C2+D2
400002  |  Schmoe, Joe| 3.8   | 0.14|   =C3+D3
Blank   |             |       |     |   #VALUE
Blank   |             |       |     |   #VALUE

The OP wanted to delete rows where Column A is blank, but there is a value in Column E.

I suggest that this is an example where we could make use of SpecialCells and a temporary Error Column to identify the rows to be deleted.

Consider that you might add a column H to try and identify those rows; in that row you could use a formula like below:

=IF(AND(A:A="",E:E<>""),"DELETE THIS ROW","LEAVE THIS ROW")

now, it is possible get that formula to put an error in the rows where I test returns True. The reason we would do this is a feature of Excel called SpecialCells.

In Excel select any empty cell, and in the formula bar type

=NA()

Next, hit F5 or CTRL+G (Go to… on the Edit menu) then click the Special button to show the SpecialCells dialog.

In that dialog, click the radio next to ‘Formulas’ and underneath, clear the checkboxes so that only Errors is selected. Now click OK

Excel should have selected all the cells in the worksheet with an Error (#N/A) in them.

The code below takes advantage of this trick by creating a formula in column H that will put an #N/A in all the rows you want to delete, then calling SpecialCells to find the rows, and clear (delete) them…

    Sub clearCells()
    '
    Dim sFormula As String
    '
    ' this formula put's an error if the test returns true, 
    ' so we can use SpecialCells function to highlight the
    ' rows to be deleted!

Create a formula that will return #NA when the formula returns TRUE

sFormula = "=IF(AND(A:A="""",E:E<>""""),NA(),"""")"

Put that formula in Column H, to find the rows that are to be deleted…

Range("H5:H" & Range("E65536").End(xlUp).Row).Formula = sFormula

Now use SpecialCells to highlight the rows to be deleted:

Range("H5:H" & Range("E65536").End(xlUp).Row).SpecialCells(xlCellTypeFormulas, xlErrors).entirerow.select

This line of code would highlight just Column A by using OFFSET in case instead of deleting the entire row, you wanted to put some text in, or clear it

Range("H5:H" & Range("E65536").End(xlUp).Row).SpecialCells(xlCellTypeFormulas, xlErrors).Offset(0, -7).select

and the below line of code will delete thhe entire row because we can :)

Range("H5:H" & Range("E65536").End(xlUp).Row).SpecialCells(xlCellTypeFormulas, xlErrors).EntireRow.Delete shift:=xlup

' clean up the formula
Range("H5:H" & Range("E65536").End(xlUp).Row).Clear
'
End Sub

BTW, it’s also possible WITH A LOOP if you really want one :)

One more thing, before Excel 2010 there was a limit of 8192 rows (I think because this feature went all the way back to 8-bit versions of Excel maybe)

The VBA legend Ron de Bruin (on whose website I first picked up this technique, among others) has something to say about this

Philip

In this VBA Tutorial, you learn how to use Excel VBA to delete rows based on a variety of criteria.Excel VBA Tutorial about how to delete rows with macros

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

Identify row to delete > Delete row

VBA Statement Explanation

Worksheets.Rows(Row#).Delete

  1. Item: Worksheets.
    • VBA Construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the worksheet you work with.
  2. 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.

  3. 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.

Macro deletes row 6

#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

Identify row to delete > Delete row and shift cells up

VBA Statement Explanation

Worksheet.Rows(Row#).Delete Shift:=xlShiftUp

  1. Item: Worksheet.
    • VBA Construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the worksheet you work with.
  2. 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.

  3. Item: Delete.
    • VBA Construct: Range.Delete method.
    • Description: Deletes the Range object returned by item #2 above.
  4. 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.

Macro deletes row 10 and shift cells up

#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

Identify rows to delete > Delete rows

VBA Statement Explanation

Worksheet.Rows(“FirstRow#:LastRow#”).Delete

  1. Item: Worksheet.
    • VBA Construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the worksheet you work with.
  2. 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.
  3. 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.

Macro deletes rows 14 to 18

#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

Identify active cell > Return entire row > Delete row

VBA Statement Explanation

ActiveCell.EntireRow.Delete

  1. Item: ActiveCell.
    • VBA Construct: Application.ActiveCell property.
    • Description: Returns a Range object representing the active cell.
  2. 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.
  3. 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.

Macro deletes 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

Identify selected cells > Return entire rows > Delete rows

VBA Statement Explanation

Selection.EntireRow.Delete

  1. Item: Selection.
    • VBA Construct: Application.Selection property.
    • Description: Returns a Range object representing the current cell range selection.
  2. 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.
  3. 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.

Macro deletes 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

Loop through all rows > Is row empty? > Add row to variable representing empty rows > Delete rows

VBA Statement Explanation

Lines #1 and #11: With Worksheet | End With

  1. 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.
  2. 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

  1. 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).
  2. 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.
  3. 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.

  4. 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.

  5. 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

  1. 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.
  2. 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.

  3. Item: .Rows(Counter).
    • VBA Construct: Worksheet.Rows property.
    • Description: Returns a Range object representing the row through which the macro is currently looping.
  4. 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

  1. 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.
  2. 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.
  3. Item: BlankRows.
    • VBA Construct: Object (Range) variable.
    • Description: Holds a Range object representing the empty rows found by the macro.
  4. 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.

  5. Item: Nothing.
    • Description: The default value for a data type. In the case of an object variable (such as BlankRows), a null reference.
  6. 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.

Line #5: Set BlankRows = Union(BlankRows, .Rows(Counter))

  1. Item: Set… =.
    • VBA Construct: Set statement.
    • Description: Assigns the object reference returned by item #6 below to BlankRows (item #2 below).
  2. 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.
  3. 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.
  4. 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.
  5. Item: .Rows(Counter).
    • VBA Construct: Worksheet.Rows property.
    • Description: Returns a Range object representing the row through which the macro is currently looping.
  6. 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:

      Union(BlankRows, .Rows(Counter))

      In other words, any empty row the macro finds is “added” to BlankRows.

Line #6: Else

  1. 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)

  1. Item: Set… =.
    • VBA Construct: Set statement.
    • Description: Assigns the object reference returned by item #3 below to BlankRows (item #2 below).
  2. Item: BlankRows.
    • VBA Construct: Object (Range) variable of Set statement.
    • Description: Holds a Range object representing the empty rows found by the macro.
  3. 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

  1. 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

  1. 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.
  2. 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.
  3. Item: BlankRows.
    • VBA Construct: Object (Range) variable.
    • Description: Holds a Range object representing the empty rows found by the macro.
  4. 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.

  5. Item: Nothing.
    • Description: The default value for a data type. In the case of an object variable (such as BlankRows), a null reference.
  6. 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.
  7. Item: BlankRows.
    • VBA Construct: Object (Range) variable.
    • Description: Holds a Range object representing the empty rows found by the macro.
  8. 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.

Macro deletes blank rows

#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

Identify cell range > Identify empty cells > Return entire rows > Delete rows

VBA Statement Explanation

Lines #1 and #3: With Worksheet | End With

  1. 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.
  2. 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))

  1. Item: Set… =.
    • VBA Construct: Set statement.
    • Description: Assigns the object reference returned by items #3 through #5 below to RangeForCriteria (item #2 below).
  2. 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.
  3. 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.
  4. 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.

  5. 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

  1. 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

  1. 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.
  2. 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).
  3. 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.
  4. 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.

Macro deletes rows with blank cells

#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

Identify cell range > Filter to find blank cells > Exclude headers > Identify visible cells > Return entire rows > Delete rows

VBA Statement Explanation

Lines #1 and #8: With Worksheet | End With

  1. 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.
  2. 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

  1. Item: With… End With.
    1. VBA Construct: With… End With statement.
    2. 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.
  2. 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.
  3. 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.

  4. 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:=”=”

  1. 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.
  2. 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.

  3. Item: Criteria1:=”=”.
    • VBA Construct: Criteria1 parameter of Range.AutoFilter method.
    • Description: Specifies the filtering criteria. “=” finds blank cells.

Line #4: On Error Resume Next

  1. 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

  1. 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.
  2. 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.
  3. Item: Resize.
    • VBA Construct: Range.Resize property.
    • Description: Resizes the cell range returned by items #1 and #2 above.
  4. 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).
  5. 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.
  6. Item: Count.
    • VBA Construct: Range.Count property.
    • Description: Returns the number of rows within the Range object returned by item #5 above.
  7. 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.

  8. 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.

  9. 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.
  10. Item: Delete.
    • VBA Construct: Range.Delete method.
    • Description: Deletes the Range object returned by item #10 above.

Line #7: .AutoFilterMode = False

  1. 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).

Macro deletes rows with blank cells in first column

#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

Identify cell range > Identify cells with strings > Return entire rows > Delete rows

VBA Statement Explanation

Lines #1 and #3: With Worksheet | End With

  1. 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.
  2. 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))

  1. Item: Set… =.
    • VBA Construct: Set statement.
    • Description: Assigns the object reference returned by items #3 through #5 below to RangeForCriteria (item #2 below).
  2. 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.
  3. 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.
  4. 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.

  5. 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

  1. 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

  1. 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.
  2. 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.
  3. 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.
  4. 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:

  1. Rows number myFirstRow and myLastRow.
  2. 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.

Macro deletes rows containing strings

#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

Identify cell range > Filter cells with value > Exclude headers > Identify visible cells > Return entire rows > Delete rows

VBA Statement Explanation

Lines #1 and #8: With Worksheet | End With

  1. 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.
  2. 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

  1. Item: With… End With.
    1. VBA Construct: With… End With statement.
    2. 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.
  2. 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.
  3. 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.

  4. 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

  1. 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.
  2. 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.

  3. 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

  1. 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

  1. 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.
  2. 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.
  3. Item: Resize.
    • VBA Construct: Range.Resize property.
    • Description: Resizes the cell range returned by items #1 and #2 above.
  4. 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).
  5. 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.
  6. Item: Count.
    • VBA Construct: Range.Count property.
    • Description: Returns the number of rows within the Range object returned by item #5 above.
  7. Item: Resize(RowSize:=(.Rows.Count – 1)).
    1. VBA Construct: Range.Resize property.
    2. 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.

  8. 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.

  9. 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.
  10. Item: Delete.
    • VBA Construct: Range.Delete method.
    • Description: Deletes the Range object returned by item #10 above.

Line #7: .AutoFilterMode = False

  1. 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).

Macro deletes rows based on value

#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

Loop through all rows > Does row contain date? > Add cell with date to object variable representing cells with date > Return entire rows > Delete rows

VBA Statement Explanation

Lines #1 and #13: With Worksheet | End With

  1. 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.
  2. 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

  1. 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).
  2. 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.
  3. 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.

  4. 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.

  5. 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

  1. 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.
  2. 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

  1. 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.
  2. 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.
  3. 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.

  5. Item: Nothing.
    • Description: The default value for a data type. In the case of an object variable (such as RowsWithDate), a null reference.
  6. 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.

Line #6: Set RowsWithDate = Union(RowsWithDate, .Cells)

  1. Item: Set… =.
    • VBA Construct: Set statement.
    • Description: Assigns the object reference returned by item #6 below to RowsWithDate (item #2 below).
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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:

      Union(RowsWithDate, .Cells)

      In other words, any cell containing the criteria date the macro finds is “added” to RowsWithDate.

Line #7: Else

  1. 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

  1. Item: Set… =.
    • VBA Construct: Set statement.
    • Description: Assigns the object reference returned by item #3 below to RowsWithDate (item #2 below).
  2. 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.
  3. 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

  1. 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.

  5. Item: Nothing.
    • Description: The default value for a data type. In the case of an object variable (such as RowsWithDate), a null reference.
  6. 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.
  7. 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.
  8. 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.
  9. 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).

Macro deletes rows based on date

#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

Identify cell range > Filter cells with string > Exclude headers > Identify visible cells > Return entire rows > Delete rows

VBA Statement Explanation

Lines #1 and #8: With Worksheet | End With

  1. 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.
  2. 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

  1. Item: With… End With.
    1. VBA Construct: With… End With statement.
    2. 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.
  2. 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.
  3. 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.

  4. 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

  1. 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.
  2. 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.

  3. 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

  1. 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

  1. 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.
  2. 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.
  3. Item: Resize.
    • VBA Construct: Range.Resize property.
    • Description: Resizes the cell range returned by items #1 and #2 above.
  4. 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).
  5. 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.
  6. Item: Count.
    • VBA Construct: Range.Count property.
    • Description: Returns the number of rows within the Range object returned by item #5 above.
  7. Item: Resize(RowSize:=(.Rows.Count – 1)).
    1. VBA Construct: Range.Resize property.
    2. 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.

  8. 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.

  9. 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.
  10. Item: Delete.
    • VBA Construct: Range.Delete method.
    • Description: Deletes the Range object returned by item #10 above.

Line #7: .AutoFilterMode = False

  1. 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).

Macro deletes rows based on string criteria

References to VBA Constructs Used in this VBA Tutorial

Use the following links to visit the appropriate webpage within the Microsoft Office Dev Center:

  1. Identify the worksheet you work with:
    • Workbook.Worksheets property.
  2. 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.
  3. Return Range objects:
    • Application.ActiveCell property.
    • Worksheet.Cells property.
    • Range.Cells property.
    • Range.Offset property.
    • Range.Resize property.
    • Application.Union method.
  4. Return Range objects representing rows:
    • Worksheet.Rows property.
    • Range.Rows property.
    • Range.EntireRow property.
  5. Loop through rows:
    • For… Next statement.
  6. Specify criteria for row deletion:
    • DateSerial Function.
    • DateValue Function.
    • Range.Value property.
  7. 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.
  8. Delete rows.
    • Range.Delete method.
  9. 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.
  10. Simplify object references:
    • With… End With statement.
  11. Handle errors:
    • On Error statement.
  12. Remove AutoFilter drop-down arrows:
    • Worksheet.AutoFilterMode property.

Содержание

  1. VBA Delete Entire Row or Column
  2. Delete Entire Row or Column
  3. Delete Multiple Rows or Columns
  4. Delete Blank / Empty Rows
  5. Delete Row if Cell is Blank
  6. Delete Row Based on Cell Value
  7. More Delete Row and Column Examples
  8. VBA Coding Made Easy
  9. Delete Duplicate Rows
  10. Delete Table Rows
  11. Delete Filtered Rows
  12. Delete Rows in Range
  13. Delete Selected Rows
  14. Delete Last Row
  15. Delete Columns by Number
  16. VBA Code Examples Add-in
  17. VBA Удалить строку — Как удалить строку в Excel VBA?
  18. VBA Удалить строку
  19. Синтаксис для удаления строки в Excel VBA
  20. Как удалить строку в Excel, используя VBA?
  21. VBA Delete Row — Пример № 1
  22. VBA Delete Row — Пример № 2
  23. VBA Delete Row — Пример № 3
  24. VBA Delete Row — Пример № 4
  25. VBA Delete Row — Пример № 5
  26. То, что нужно запомнить
  27. Рекомендуемые статьи
  28. Delete a row in Excel VBA
  29. 4 Answers 4

VBA Delete Entire Row or Column

In this Article

This tutorial will demonstrate different ways to delete rows and columns in Excel using VBA.

Delete Entire Row or Column

To delete an entire row in VBA use this line of code:

Notice we use the Delete method to delete a row.

Instead of referencing the Rows Object, you can reference rows based on their Range Object with EntireRow:

Similarly to delete an entire column, use these lines of code:

Delete Multiple Rows or Columns

Using the same logic, you can also delete multiple rows at once:

Notice here we reference the specific row and column numbers / letters surrounded by quotations.

Of course, you can also reference the EntireRow of a range:

Note: The examples below only demonstrate deleting rows, however as you can see above, the syntax is virtually identically to delete columns.

Delete Blank / Empty Rows

Delete Row if Cell is Blank

Delete Row Based on Cell Value

More Delete Row and Column Examples

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Delete Duplicate Rows

This code will delete all duplicate rows in a range:

Notice we set Columns:=2. This tells VBA to check both the first two columns of data when considering if rows are duplicates. A duplicate is only found when both columns have duplicate values.

If we had set this to 1, only the first row would’ve been checked for duplicate values.

Delete Table Rows

This code will delete the second row in a Table by referencing ListObjects.

Delete Filtered Rows

To delete only rows that are visible after filtering:

Delete Rows in Range

This code will delete all rows in range:

Delete Selected Rows

This code will delete all selected rows:

Delete Last Row

This will delete the last used row in column B:

By changing 2 to 1, you can delete the last used row in column A, etc.:

Delete Columns by Number

To delete a column by it’s number, use a code like this:

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

VBA Удалить строку — Как удалить строку в Excel VBA?

VBA Удалить строку

В Excel, чтобы удалить любую строку, у нас есть сочетание клавиш CTRL + — или мы можем выбрать строку и щелкнуть по ней правой кнопкой мыши и удалить ее. Но в VBA мы сделали это, написав код для этого. Метод удаления строки в VBA заключается в том, что сначала нам нужно определить, какую строку удалить, а затем мы можем ее удалить. В этой статье мы узнаем о различных иллюстрациях о том, как удалить строку в VBA.

В VBA Удалить строку используется для удаления либо набора строк, либо отдельной строки в зависимости от ситуации. Подобно листу Excel, мы можем использовать макросы или VBA для удаления строк в листе Excel. Это помогает, когда у нас много данных, и мы не можем сделать это вручную.

Синтаксис для удаления строки в Excel VBA

Синтаксис для удаления строки в Excel, как показано ниже.

Worksheets.Rows (Row #). Удалить

Есть также другие методы удаления строк с использованием VBA, такие как следующие.

Range ( «Cell»). EntireRow.Delete

То, что будет делать вышеприведенный оператор, — это удаление строки для данной строки. Например, если мы напишем Range («A1»). FullRow.Delete, то первая строка будет удалена, так как ячейка A1 принадлежит первой строке.

Также мы можем использовать Rows (row_num) .delete для удаления строки.

Как удалить строку в Excel, используя VBA?

Ниже приведены некоторые примеры того, как удалить строку в Excel с помощью VBA.

Вы можете скачать этот шаблон VBA Удалить строку Excel здесь — VBA Удалить шаблон Excel строку

VBA Delete Row — Пример № 1

Давайте используем первый простой метод для удаления строк. Для демонстрации я введу случайное значение в ячейки A1 и B1. Посмотрите на это ниже.

Что я хочу видеть, так это то, что если я буду использовать код, написанный выше, вся строка будет удалена или будет удалена одна ячейка.

Примечание. Для использования Excel VBA необходимо включить вкладку разработчика на вкладке «Файлы» в разделе параметров.

Выполните следующие шаги, чтобы удалить строку в Excel с помощью VBA.

Шаг 1. Перейдите на вкладку разработчика, щелкните Visual Basic, чтобы открыть редактор VBA.

Шаг 2: В сегменте кода объявите подфункцию, чтобы начать писать код.

Код:

Шаг 3: Теперь напишите следующий код, чтобы удалить строку.

Код:

Шаг 4: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.

Запустив код, мы увидим, что значения из ячеек A1 и B1 удаляются, поскольку вся первая строка была удалена.

VBA Delete Row — Пример № 2

Ранее в первом примере я удалил только одну строку. Но что делать, если нам нужно удалить несколько строк? Для демонстрации, у меня есть следующие данные, как показано ниже,

Я хочу удалить все первые пять строк. Выполните следующие шаги, чтобы удалить строку в Excel с помощью VBA.

Шаг 1. На вкладке разработчика щелкните Visual Basic, чтобы открыть редактор VBA.

Шаг 2: В коде объявите подфункцию, чтобы начать писать код,

Код:

Шаг 3: Напишите следующий код, показанный ниже, чтобы удалить все пять строк.

Код:

Шаг 4: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.

Как только мы запустим код, мы увидим следующий результат: все данные были удалены, что означает, что первые пять строк были удалены, поскольку у нас были данные в первых пяти строках.

Примечание: я вставлю данные обратно в образец листа Excel для демонстрации.

VBA Delete Row — Пример № 3

Теперь у нас есть данные о сотрудниках, и их продажи осуществляются за три месяца: январь, февраль и март. Один из сотрудников был в отпуске и не мог заниматься продажей в течение трех месяцев, поэтому камеры для него пусты. Наша цель — найти эту пустую строку и удалить ее из данных.

Посмотрите на данные ниже,

Выполните следующие шаги, чтобы удалить строку в Excel с помощью VBA.

Шаг 1. На вкладке разработчика щелкните Visual Basic, чтобы открыть редактор Visual Basic.

Шаг 2: Объявите подфункцию в окне кода, чтобы начать писать код,

Код:

Шаг 3: Напишите следующий код, чтобы удалить строки с пустыми ячейками.

Код:

SpecialCells — это функция в VBA, которая возвращает нам все ячейки, которые соответствуют нашим условиям, и нашим условием были пустые ячейки в этом диапазоне, поэтому мы использовали функцию xlCellTypeBlanks.

Шаг 4: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.

Запустив код, мы увидим, что строка с пустыми ячейками была удалена.

Примечание: я снова вставлю данные в образец листа Excel для демонстрации.

VBA Delete Row — Пример № 4

Существуют и другие подобные методы удаления строк, например, использование строк и функция удаления. Например, у нас есть данные в строке 4, и я хочу удалить строку 4. Мы можем дать команду Excel для удаления 4- й строки в данных. Посмотрите на скриншот ниже. У меня есть случайные данные в строке 4 в первой ячейке.

Выполните следующие шаги, чтобы удалить строку в Excel с помощью VBA.

Шаг 1. Откройте редактор VBA, щелкнув Visual Basic на вкладке разработчика.

Шаг 2: Объявите подфункцию, чтобы начать писать код.

Код:

Шаг 3: Напишите следующий код для удаления 4-й строки.

Код:

Шаг 4: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.

Данные были удалены, так как 4- я строка была удалена сама.

VBA Delete Row — Пример № 5

В приведенном выше коде мы дали диапазон или строку для удаления в самом коде. Теперь давайте примем ввод от пользователя, и он может удалить строку из заданных данных. Например, у меня есть данные о сотрудниках и продажах, как показано ниже, и я хочу, чтобы пользователь выбрал диапазон, из которого пользователь хочет удалить строки с пустыми ячейками. Посмотрите на данные ниже,

Выполните следующие шаги, чтобы удалить строку в Excel с помощью VBA.

Шаг 1: Откройте VB Editor, нажав Visual Basic на вкладке разработчика,

Шаг 2: Объявите подфункцию, чтобы начать писать код.

Код:

Шаг 2: Объявите две переменные как диапазон, A и B.

Код:

Шаг 3: Чтобы принять ввод от пользователя для выбора диапазона, который нужно удалить, мы будем использовать функцию поля ввода и сохраним этот ввод в переменной, определенной выше.

Код:

Шаг 4: Установите B = A, чтобы ввод от пользователя можно было сохранить в диапазоне B.

Код:

Шаг 5: Теперь мы удалим данные с пустыми ячейками из диапазона, выбранного пользователем.

Код:

Шаг 6: Теперь запустите код с помощью кнопки запуска.

Шаг 6: Появляется поле ввода.

Шаг 7: Выберите диапазон от A1: D8 в этом примере. Нажмите OK, чтобы увидеть результат.

Данные с пустыми ячейками были удалены.

То, что нужно запомнить

Есть несколько вещей, которые мы должны помнить об удалении строки в Excel VBA:

  • Мы можем удалить строку на основе одной ячейки.
  • Мы можем удалить несколько строк, задав диапазон ячеек.
  • Мы также можем удалять строки, принимая данные от пользователя.

Рекомендуемые статьи

Это был путеводитель по VBA Delete Row. Здесь мы обсудили, как удалить строку в Excel VBA вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Как использовать функцию замены в VBA?
  2. Excel Удалить строку ярлык
  3. VBA Case | Excel Tricks
  4. Ярлык строки вставки Excel
  5. Как суммировать несколько строк в Excel?

Источник

Delete a row in Excel VBA

I have this piece of code which finds the excel row of an item from a list and deletes the items from a list. What I want. is to delete the Excel row as well.

The code is here

Where I added ws.Range(Rand,1).EntireRow.Delete is where I want to delete the entire row but I don’t know how to do it. What I want. if it finds the same value in a cell like in some selected item of my list to be able to remove both the entire row in excel and the item from the listbox. It works to remove the item from the listbox but I don’t know how to remove the row as well

4 Answers 4

Chris Nielsen’s solution is simple and will work well. A slightly shorter option would be.

. note there is no need to specify a Shift when deleting a row as, by definition, it’s not possible to shift left

Incidentally, my preferred method for deleting rows is to use.

. in the initial loop. I then use a Sort function to push these rows to the bottom of the data. The main reason for this is because deleting single rows can be a very slow procedure (if you are deleting >100). It also ensures nothing gets missed as per Robert Ilbrink’s comment

You can learn the code for sorting by recording a macro and reducing the code as demonstrated in this expert Excel video. I have a suspicion that the neatest method (Range(«A1:Z10»).Sort Key1:=Range(«A1»), Order1:=xlSortAscending/Descending, Header:=xlYes/No) can only be discovered on pre-2007 versions of Excel. but you can always reduce the 2007/2010 equivalent code

Couple more points. if your list is not already sorted by a column and you wish to retain the order, you can stick the row number ‘Rand’ in a spare column to the right of each row as you loop through. You would then sort by that comment and eliminate it

If your data rows contain formatting, you may wish to find the end of the new data range and delete the rows that you cleared earlier. That’s to keep the file size down. Note that a single large delete at the end of the procedure will not impair your code’s performance in the same way that deleting single rows does

Источник

Adding and deleting rows is part of everyday common tasks when working with Excel.

While you can do this easily from the worksheet itself, sometimes you may want to use the VBA route to delete rows in Excel. These could be deleting a specific row, multiple rows in the selection, deleting alternate rows or those that have a specific value in it.

In this tutorial, I will show you how to delete rows in Excel using VBA (multiple scenarios).

So let’s get started!

Delete an Entire Row using VBA

To delete an entire row in Excel using VBA, you need to use the EntireRow.Delete method.

For example, if you want to delete the entire first row in a worksheet, you can use the below code:

Sub DeleteEntireRow()
Rows(1).EntireRow.Delete
End Sub

The above code first specifies the row that needs to be deleted (which is done by specifying the number in bracket) and then uses the EntireRow.Delete method to delete it.

You can also delete multiple rows by specifying these rows in the code.

For example, the below code will delete row number 1, 5 and 9 in the worksheet:

Sub DeleteEntireRow()
Rows(9).EntireRow.Delete
Rows(5).EntireRow.Delete
Rows(1).EntireRow.Delete
End Sub

The above code uses the same logic, where it specifies the row numbers and Excel will delete these rows one by one.

IMPORTANT: When you’re deleting rows with something similar to the above code, remember to start deleting from the bottom and then go up. For example, in case you start at the top and delete row 1 first, all the rows below it would be shifted one row up and the numbering would be off (as row 5 would become row 4 and so on)

Delete All Rows in the Selection

In case you want to delete all the rows in a selected range of cells, you can use the VBA macro code below:

Sub DeleteEntireRow()
Selection.EntireRow.Delete
End Sub

The above code applies to the EntireRow.Delete method to the entire selection.

Delete Alternate rows (or Delete Every Third/Fourth/Nth Row)

Sometimes, you may get a data dump where every second row (or third, fourth or Nth rows) is useless and needs to be deleted.

I used to work with financial data where every second row was empty and had to be deleted.

This is the type of scenario where VBA really shines.

Below is the VBA code that will go through all the rows in the selection and delete every second row:

Sub DeleteAlternateRows()
RCount = Selection.Rows.Count
For i = RCount To 1 Step -2
    Selection.Rows(i).EntireRow.Delete
Next i
End Sub

Let me explain how this VBA code works.

First, I have used a variable RCount to get the total number of rows in the selection.

Then I have used a For Next loop to run this as many times as many rows are there. For example, if there are 12 rows, this loop will run from 12 to 1 (i.e., 12 times). It’s important to run this from the last row in the selection to the first as we don’t want the row numbers to change when a row is deleted.

Also, Step -2 is used since we need to delete every other row (from bottom to top). In case you want to delete every third row, you can use -3.

Within the VBA loop, I have used the Selection.Rows(i).EntireRow.Delete method to delete every alternate row.

Delete Blank Rows with VBA

You can also use the EntireRow.Delete method to delete all blank rows.

Below is the VBA code that will select blank cells in the selected dataset and delete the entire row.

Sub DeleteBlankRows()
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub

The above code uses the SpecialCells property to select and delete all the cells that are blank. This is the same method that also allows us to use ‘Go To Special’ dialog box to select all blank cells.

Once these blank cells are identified using SpecialCell, these are then deleted using the EntireRow.Delete method.

Note: This method selects cells that are blank and don’t check whether the entire row is blank or not. So if anyone cell is empty in a row, this would still delete the entire row.

Delete Rows with a Specific Word/Value

You can also use a simple VBA code to go through each cell in the selected range and delete all the rows where a cell contains a specific text or value.

For example, suppose you have a dataset and I want to delete all cells that have the text Printer in column 2 of the selection.

Dataset from where delete entire row with specific value

Below is the code that will do this:

Sub DeleteRowswithSpecificValue()
For i = Selection.Rows.Count To 1 Step -1
If Cells(i, 2).Value = "Printer" Then
Cells(i, 2).EntireRow.Delete
End If
Next i
End Sub

The above code first counts the total number of rows in the selection. This will make sure the loop is run only these many times. It then uses the ‘For Next loop’ to go through all the cells in Column 2.

The IF THEN ELSE statement is then used to check the value in each cell in column 2. And in case the value/text matches the specified text (which is ‘Printer’ in this example).

In this example, I have checked whether the text matches a specific string or not. You can also do this with values. For example, you can delete all rows where the sale value is less than 1000 or more than 1000.

Note: An important thing to note here is that the loop runs from Selection.Rows.Count To 1 to make sure when a row is deleted, it doesn’t impact the rows above it.

How to Use This VBA Code

Now let me show you how to use all the codes mentioned in this tutorial to delete the entire row.

You need to copy and paste these codes in a module in Excel VB Editor. Once you have these codes copied, you can then run the macro codes.

Below are the steps to copy and paste these VBA codes in a module:

  1. Hold the ALT key and press the F11 key (or Function + Option + F11 in Mac). This will open the VB Editor
  2. In the VB Editor, you will have the project explorer on the left. If you don’t see it, go to the View option and then click on Project Explorer.Click on Project Explorer
  3. Right-click on any object in the Project Explorer (for the workbook in which you want to run the code).Insert Module
  4. Go to Insert and then click on Module. This will insert a new Module for the workbookCopy and paste to delete entire row in the module
  5. Copy and Paste the above codes in the module.

And to run these codes, you can place the cursor anywhere in the code (that you want to run) and hit the F5 key (or click on the green triangle in the VBA toolbar).

I have also written a detailed tutorial on different ways to run VBA macro codes in Excel.

In case you need to use any of these codes quite often, you can also consider adding these to the Personal Macro Workbook and then to the QAT. This way, the code will be available to you in any of your workbooks with a single click.

So these were some VBA codes that you can use to delete entire rows in Excel (in different scenarios). The same logic can also be applied in case you want to delete columns instead of rows (with the corresponding adjustment in the code examples).

Hope you found this tutorial useful!

You may also like the following Excel tutorials:

  • Excel VBA Autofilter: A Complete Guide with Examples
  • Delete Rows Based on a Cell Value (or Condition) in Excel
  • Insert a Blank Row after Every Row in Excel (or Every Nth Row)
  • How to Quickly Unhide COLUMNS in Excel

Excel VBA Delete Row

Normally in an Excel worksheet, we have two different methods to delete rows: the keyboard shortcut and the right-click and insert method. But in VBA, we must use the “Delete” command and worksheet statement to delete any rows. The trick is that if we need to delete a single row, we give a single row reference, but for multiple columns, we give multiple row references.

Using VBA Delete Row method, we can delete all the blank rows and the row based on cell value. We can also delete the entire row if any cells are blank.

This article will discuss the method “VBA Delete Row.” Keep yourself occupied for the next 15 to 20 minutes to learn about the concept.

Table of contents
  • Excel VBA Delete Row
    • How to Delete Row?
      • Example #1
      • Example #2
      • Example #3
      • Example #4
      • Example #5
      • Example #6
    • Recommended Articles

VBA Delete Row

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Delete Row (wallstreetmojo.com)

How to Delete Row?

You can download this VBA Delete Row Excel Template here – VBA Delete Row Excel Template

Example #1

In VBA, we need to mention the row we are deleting.

Code:

Sub DeleteRow_Example1()
Cells(1, 1)
End Sub

vba delete example 1.1

Cells (1, 1) means first-row first column, i.e., A1 cell. Then, we use the method “Delete.”

Code:

Sub DeleteRow_Example1()
Cells(1, 1).Delete
End Sub

vba delete example 1.2

Now, this will delete the first cell. All the right-side values will shift from one cell to the left.

vba delete example 1.2

Example #2

If you want to delete the entire row, we need to use the property “EntireRow,” then, we need to use the method “Delete” to delete the entire row of the cell we have selected.

Code:

Sub DeleteRow_Example2()
Cells(1, 1).EntireRow.Delete
End Sub

vba delete example 1.3

For example, we have entered a few characters in an Excel sheet.

vba delete example 1.4

If we run this code, it will delete the entire row, not a single cell.

vba delete example 1.4

Example #3

We can delete the row by using several ways. In the above example, we deleted the row using the CELLS property. Now, we will see how to delete by using the ROWS property.

vba delete example 1.5

Now, we need to mention what is the row we need to delete. For example, we need to delete the 5th row.

vba delete example 1.6

Now, use the “EntireRow” property.

vba delete example 1.7

After selecting the property, what do we need to do? First, we need to delete the row.

Code:

Sub DeleteRow_Example3()
Rows(5).EntireRow.Delete
End Sub

vba delete example 1.8

So, this code will delete the 5th row.

Example #4

Delete Multiple Rows by Using Range Object

How do we delete multiple rows?

We can use the VBA RANGE objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more to delete more than one row. For example, assume you have some values from A1 to A6 cells.

vba delete example 2.1

Now, we want to delete the first five rows, so we can reference these rows by using the Range object as “Range (“A1: A5”).

Code:

Sub DeleteRow_Example4()
Range ("A1: A5")
End Sub

vba delete example 2.2

Now, we want to use the word “EntireRow” property.

Code:

Sub DeleteRow_Example4()

Range("A1:A5").EntireRow

End Sub

vba delete example 2.3

In this row, we need to perform the method of deleting, so use the “Delete” method.

Code:

Sub DeleteRow_Example4()

Range("A1:A5").EntireRow.Delete

End Sub

vba delete example 2.4

Now, this will delete the selected rows.

vba delete example 2.4

Example #5

Delete Rows Based On Cell Value

We can also use this “EntireRow.Delete” method to delete the row based on the cell value in VBAIn VBA, there are two ways to interact with or get value from a cell: the range method and the cell method.read more. For example, we have “Yes” and “No” values from cells A1 to A10.

example 3.1

We need to delete the rows with the value “No.” We must use the function “IF” with loops to delete all the rows with the value of “No” to perform this task.

The below code will do the job for us.

Code:

Sub DeleteRow_Example5()

Dim k As Integer 

For k = 10 To 1 Step -1
If Cells(k, 1).Value = "No" Then
Cells(k, 1).EntireRow.Delete
End If
Next k

End Sub

example 3.2

Example #6

Delete All the Blank Cells Rows

There are situations where we need to delete the entire row if any of the cells in the range are blank. For example, we have the below set of data.

example 4.1

All the colored cells are blank, so we must delete the entire row. We can perform this task with two sets of code. Below is the code.

Code:

Sub DeleteRow_Example6()

Range("A1:F10").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

example 4.2

It will identify the blank cells in the range A1 to F10. If it finds any blank cells, it will delete the entire row.

example 4.2 gif

The problem with this code is it will only delete the blank cell’s row in the range A1 to F10. But if any cells are blank in any other cells, it will not delete them. So, keeping this in mind, we have written one more code.

Code:

Sub DeleteRow_Example7()

Dim RangeToDelete As Range
Dim DeletionRange As Range

Set RangeToDelete = Application.InputBox("Please select the range", "Blank Cells Rows Deletion", Type:=8)

Set DeletionRange = RangeToDelete

RangeToDelete.SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

example 4.3

When you run this code, firstly, it will ask you to select the range with an input box appearing in front of you.

example 4.4

After selecting the range, you need to click on “OK.” It will delete all the blank cells rowsThere are several methods for deleting blank rows from Excel: 1) Manually deleting blank rows if there are few blank rows  2)  Use the formula delete 3) Use the filter to find and delete blank rows.read more in the selected range.

Recommended Articles

This article has been a guide to VBA Delete Row. Here, we discussed how to delete rows using VBA codes and practical examples. Below are some useful Excel articles related to VBA: –

  • Excel VBA Delete Column
  • VBA Last Row
  • How to Code in VBA?
  • Format Number in VBA
  • VBA INT

Понравилась статья? Поделить с друзьями:
  • Vba excel буквы в строке
  • Vba excel буква колонки по номеру
  • Vba excel блокировка ячеек
  • Vba excel библиотека макросов
  • Vba excel атрибут файла