NewStudent07 0 / 0 / 0 Регистрация: 14.04.2013 Сообщений: 22 |
||||
1 |
||||
Нужно удалить пустые ячейки из выбронного столбца14.04.2013, 18:06. Показов 10169. Ответов 6 Метки нет (Все метки)
Пожалуйста, помогите. Я только учись писать макросы. Вот написала один, а он некоректно работает.
0 |
2670 / 786 / 176 Регистрация: 14.01.2013 Сообщений: 3,676 |
|
14.04.2013, 18:15 |
2 |
После удаления ячейки, следующая становится текущей. Вот тут собака и зарыта.
0 |
0 / 0 / 0 Регистрация: 14.04.2013 Сообщений: 22 |
|
14.04.2013, 18:18 [ТС] |
3 |
и как это исправить??
0 |
Казанский 15136 / 6410 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
||||
14.04.2013, 18:25 |
4 |
|||
РешениеЛибо пустить цикл от последней строки к первой, либо обойтись вообще без цикла: F5 — выделить — пустые ячейки — удалить. В VBA это выглядит так:
3 |
0 / 0 / 0 Регистрация: 14.04.2013 Сообщений: 22 |
|
14.04.2013, 18:45 [ТС] |
5 |
Огромное спасибо!! Правда я не совсем понимаю ваш код, так как только начала изучать VBA. Но главное, что он работает!!!
Либо пустить цикл от последней строки к первой А как можно пустить цикл For each Next от последней строки к первой???
0 |
Аксима 6076 / 1320 / 195 Регистрация: 12.12.2012 Сообщений: 1,023 |
||||
14.04.2013, 19:28 |
6 |
|||
А как можно пустить цикл For each Next от последней строки к первой??? А вот так (только вместо цикла For each… next надо использовать цикл For… next):
Но вариант Казанского со SpecialCells мне нравится больше. С уважением,
1 |
0 / 0 / 0 Регистрация: 14.04.2013 Сообщений: 22 |
|
14.04.2013, 21:45 [ТС] |
7 |
Казанский и Aksima ОГРОМНОЕ ВАМ СПАСИБО!!!
0 |
This is just a sample I am testing the code in this data. I have three columns in sheet2. I have to delete the empty cells. This is the updated code which is working for column B only. You can check the snapshot
Sub delete()
Dim counter As Integer, i As Integer
counter = 0
For i = 1 To 10
If Cells(i, 1).Value <> "" Then
Cells(counter + 1, 2).Value = Cells(i, 1).Value
counter = counter + 1
End If
Next i
End Sub
Sample screenshot
Harun24hr
27.7k4 gold badges20 silver badges34 bronze badges
asked Oct 31, 2017 at 8:41
16
If all you want is to delete the empty cells, give this a try…
Sub DeleteBlankCells()
Dim rng As Range
On Error Resume Next
Set rng = Intersect(ActiveSheet.UsedRange, Range("A:C"))
rng.SpecialCells(xlCellTypeBlanks).Delete shift:=xlUp
End Sub
answered Oct 31, 2017 at 9:54
1
Not the most elegant solution but it works.
Option Explicit
Sub delete()
Dim rCells As Range, rCell As Range, sFixCell As String
Set rCells = Range("A1:A13")
For Each rCell In rCells
If rCell = "" Then
sFixCell = rCell.Address
Do While rCell.Value = ""
rCell.delete Shift:=xlUp
Set rCell = Range(sFixCell)
Loop
End If
Next rCell
End Sub
answered Oct 31, 2017 at 9:37
2
Удаление пустых строк с помощью кода VBA из всего задействованного диапазона рабочего листа Excel и из отдельного заданного диапазона.
Главный секрет удаления пустых строк кодом VBA Excel – это построчный просмотр диапазона или отдельного столбца снизу вверх, что исключает возможность при удалении найденных пустых строк получить бесконечный цикл и зависание программы.
Удаление пустых строк в используемом диапазоне
Рассмотрим удаление пустых строк из всего используемого диапазона на рабочем листе. Это может быть как таблица, так и любые наборы данных и произвольные записи, внутри которых присутствуют пустые строки, от которых надо избавиться.
Определить границы используемого диапазона на рабочем листе из кода VBA Excel нам поможет последняя ячейка используемого диапазона: Cells.SpecialCells(xlLastCell)
.
Самый простой код удаления пустых строк
Сначала определяем номер строки последней ячейки задействованного на рабочем листе диапазона. Затем, с этой строки начинаем построчный просмотр используемого диапазона снизу вверх с поиском и удалением пустых строк.
Пример кода VBA Excel для активного листа:
Sub Primer1() Dim n As Long, i As Long ‘Определяем номер строки последней ячейки ‘используемого диапазона на рабочем листе n = Cells.SpecialCells(xlLastCell).Row ‘Ищем и удаляем пустые строки For i = n To 1 Step —1 If Rows(i).Text = «» Then Rows(i).Delete Next End Sub |
То же самое, но с указанием книги и рабочего листа:
Sub Primer2() Dim n As Long, i As Long With ThisWorkbook.Worksheets(«Лист1») n = .Cells.SpecialCells(xlLastCell).Row For i = n To 1 Step —1 If .Rows(i).Text = «» Then .Rows(i).Delete Next End With End Sub |
Программа определения времени выполнения макроса показала, что этот код отработал в диапазоне из 3000 строк за 17,5 секунд.
Улучшенный код удаления пустых строк
Предыдущий код VBA Excel анализирует на наличие текста каждую строку по всей длине в пределах рабочего листа. Эта процедура проверяет каждую строку по длине только в переделах используемого диапазона:
Sub Primer3() Dim n As Long, i As Long, myRange As Range ‘Присваиваем объектной переменной ссылку на диапазон от первой ячейки ‘рабочего листа до последней ячейки используемого диапазона Set myRange = Range(Range(«A1»), Cells.SpecialCells(xlLastCell)) With myRange n = .Rows.Count For i = n To 1 Step —1 If .Rows(i).Text = «» Then .Rows(i).Delete Next End With End Sub |
Программа определения времени выполнения макроса показала, что этот код отработал в диапазоне из 3000 строк за 13,3 секунды.
Удаление строк по пустым ячейкам
Иногда может появиться необходимость удалить не только полностью пустые строки, но и строки с пустыми ячейками в определенном столбце. Тогда следует действовать так:
Sub Primer4() Dim n As Long, i As Long n = Cells.SpecialCells(xlLastCell).Row For i = n To 1 Step —1 If Cells(i, 1).Text = «» Then Rows(i).Delete Next End Sub |
или так:
Sub Primer5() Dim n As Long, i As Long, myRange As Range Set myRange = Range(Range(«A1»), Cells.SpecialCells(xlLastCell)) With myRange n = .Rows.Count For i = n To 1 Step —1 If .Cells(i, 1).Text = «» Then .Rows(i).Delete Next End With End Sub |
В этих примерах поиск пустой ячейки производится в первом столбце: Cells(i, 1)
.
Удаление пустых строк в заданном диапазоне
Процедуры VBA Excel для удаления пустых строк из заданного диапазона рассмотрим на примере объекта Selection
, который можно заменить на любой диапазон, указанный явно.
Удаление полностью пустых строк в пределах заданного диапазона:
Sub Primer6() Dim n As Long, i As Long With Selection n = .Rows.Count For i = n To 1 Step —1 If .Rows(i).Text = «» Then .Rows(i).Delete Next End With End Sub |
Удаление строк по пустым ячейкам в одном из столбцов:
Sub Primer7() Dim n As Long, i As Long With Selection n = .Rows.Count For i = n To 1 Step —1 If .Cells(i, 1).Text = «» Then .Rows(i).Delete Next End With End Sub |
Удаление пустых ячеек из диапазона
Постановка задачи
Имеем диапазон ячеек с данными, в котором есть пустые ячейки:
Задача — удалить пустые ячейки, оставив только ячейки с информацией.
Способ 1. Грубо и быстро
- Выделяем исходный диапазон
- Жмем клавишу F5, далее кнопка Выделить (Special). В открывшмся окне выбираем Пустые ячейки (Blanks) и жмем ОК.
Выделяются все пустые ячейки в диапазоне.
- Даем в меню команду на удаление выделенных ячеек: правой кнопкой мыши — Удалить ячейки (Delete Cells) со сдвигом вверх.
Способ 2. Формула массива
Для упрощения дадим нашим рабочим диапазонам имена, используя Диспетчер Имен (Name Manager) на вкладке Формулы (Formulas) или — в Excel 2003 и старше — меню Вставка — Имя — Присвоить (Insert — Name — Define)
Диапазону B3:B10 даем имя ЕстьПустые, диапазону D3:D10 — НетПустых. Диапазоны должны быть строго одного размера, а расположены могут быть где угодно относительно друг друга.
Теперь выделим первую ячейку второго диапазона (D3) и введем в нее такую страшноватую формулу:
=ЕСЛИ(СТРОКА()-СТРОКА(НетПустых)+1>ЧСТРОК(ЕстьПустые)-СЧИТАТЬПУСТОТЫ(ЕстьПустые);»»;ДВССЫЛ(АДРЕС(НАИМЕНЬШИЙ((ЕСЛИ(ЕстьПустые<>»»;СТРОКА(ЕстьПустые);СТРОКА()+ЧСТРОК(ЕстьПустые)));СТРОКА()-СТРОКА(НетПустых)+1);СТОЛБЕЦ(ЕстьПустые);4)))
В английской версии это будет:
=IF(ROW()-ROW(НетПустых)+1>ROWS(ЕстьПустые)-COUNTBLANK(ЕстьПустые),»»,INDIRECT(ADDRESS(SMALL((IF(ЕстьПустые<>»»,ROW(ЕстьПустые),ROW()+ROWS(ЕстьПустые))),ROW()-ROW(НетПустых)+1),COLUMN(ЕстьПустые),4)))
Причем ввести ее надо как формулу массива, т.е. после вставки нажать не Enter (как обычно), а Ctrl+Shift+Enter. Теперь формулу можно скопировать вниз, используя автозаполнение (потянуть за черный крестик в правом нижнем углу ячейки) — и мы получим исходный диапазон, но без пустых ячеек:
Способ 3. Пользовательская функция на VBA
Если есть подозрение, что вам часто придется повторять процедуру удаления пустых ячеек из диапазонов, то лучше один раз добавить в стандартный набор свою функцию для удаления пустых ячеек, и пользоваться ей во всех последующих случаях.
Для этого откройте редактор Visual Basic (ALT+F11), вставьте новый пустой модуль (меню Insert — Module) и скопируйте туда текст этой функции:
Function NoBlanks(DataRange As Range) As Variant() Dim N As Long Dim N2 As Long Dim Rng As Range Dim MaxCells As Long Dim Result() As Variant Dim R As Long Dim C As Long MaxCells = Application.WorksheetFunction.Max( _ Application.Caller.Cells.Count, DataRange.Cells.Count) ReDim Result(1 To MaxCells, 1 To 1) For Each Rng In DataRange.Cells If Rng.Value <> vbNullString Then N = N + 1 Result(N, 1) = Rng.Value End If Next Rng For N2 = N + 1 To MaxCells Result(N2, 1) = vbNullString Next N2 If Application.Caller.Rows.Count = 1 Then NoBlanks = Application.Transpose(Result) Else NoBlanks = Result End If End Function
Не забудьте сохранить файл и вернитесь из редактора Visual Basic в Excel. Чтобы использовать эту функцию в нашем примере:
- Выделите достаточный диапазон пустых ячеек, например F3:F10.
- Идем в меню Вставка — Функция (Insert — Function) или жмем на кнопку Вставить функцию (Insert Function) на вкладке Формулы (Formulas) в новых версиях Excel. В категории Определенные пользователем (User Defined) выберите нашу функцию NoBlanks.
- В качестве аргумента функции укажите исходный диапазон с пустотами (B3:B10) и нажмите Ctrl+Shift+Enter, чтобы ввести функцию как формулу массива.
Ссылки по теме:
- Удаление сразу всех пустых строк в таблице простым макросом
- Удаление сразу всех пустых строк на листе с помощью надстройки PLEX
- Быстрое заполнение всех пустых ячеек
- Что такое макросы, куда вставлять код макросов на VBA
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!
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
I would like to delete the empty rows my ERP Quotation generates. I’m trying to go through the document (A1:Z50
) and for each row where there is no data in the cells (A1-B1...Z1 = empty
, A5-B5...Z5 = empty
) I want to delete them.
I found this, but can’t seem to configure it for me.
On Error Resume Next
Worksheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
On Error GoTo 0
asked Feb 21, 2012 at 14:55
4
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
answered Feb 21, 2012 at 15:15
Alex K.Alex K.
170k30 gold badges263 silver badges286 bronze badges
1
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
answered Feb 21, 2012 at 15:13
Siddharth RoutSiddharth Rout
146k17 gold badges206 silver badges250 bronze badges
3
I know I am late to the party, but here is some code I wrote/use to do the job.
Sub DeleteERows()
Sheets("Sheet1").Select
Range("a2:A15000").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
Kingsley
14.3k5 gold badges33 silver badges52 bronze badges
answered Dec 12, 2018 at 21:45
3
for those who are intersted to remove «empty» and «blank» rows ( Ctrl + Shift + End going deep down of your worksheet ) .. here is my code.
It will find the last «real»row in each sheet and delete the remaining blank rows.
Function XLBlank()
For Each sh In ActiveWorkbook.Worksheets
sh.Activate
Cells(1, 1).Select
lRow = Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Range("A" & lRow + 1, Range("A1").SpecialCells(xlCellTypeLastCell).Address).Select
On Error Resume Next
Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
Cells(1, 1).Select
Next
ActiveWorkbook.Save
ActiveWorkbook.Worksheets(1).Activate
End Function
Open VBA ( ALT + F11 ), Insert -> Module,
Copy past my code and launch it with F5.
Et voila
answered Mar 5, 2019 at 8:47
I have another one for the case when you want to delete only rows which are complete empty, but not single empty cells. It also works outside of Excel e.g. on accessing Excel by Access-VBA or VB6.
Public Sub DeleteEmptyRows(Sheet As Excel.Worksheet)
Dim Row As Range
Dim Index As Long
Dim Count As Long
If Sheet Is Nothing Then Exit Sub
' We are iterating across a collection where we delete elements on the way.
' So its safe to iterate from the end to the beginning to avoid index confusion.
For Index = Sheet.UsedRange.Rows.Count To 1 Step -1
Set Row = Sheet.UsedRange.Rows(Index)
' This construct is necessary because SpecialCells(xlCellTypeBlanks)
' always throws runtime errors if it doesn't find any empty cell.
Count = 0
On Error Resume Next
Count = Row.SpecialCells(xlCellTypeBlanks).Count
On Error GoTo 0
If Count = Row.Cells.Count Then Row.Delete xlUp
Next
End Sub
answered Aug 27, 2019 at 11:34
AranxoAranxo
6053 silver badges14 bronze badges
2
To make Alex K’s answer slightly more dynamic you could use the code below:
Sub DeleteBlankRows()
Dim wks As Worksheet
Dim lngLastRow As Long, lngLastCol As Long, lngIdx As Long, _
lngColCounter As Long
Dim blnAllBlank As Boolean
Dim UserInputSheet As String
UserInputSheet = Application.InputBox("Enter the name of the sheet which you wish to remove empty rows from")
Set wks = Worksheets(UserInputSheet)
With wks
'Now that our sheet is defined, we'll find the last row and last column
lngLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
lngLastCol = .Cells.Find(What:="*", LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
'Since we need to delete rows, we start from the bottom and move up
For lngIdx = lngLastRow To 1 Step -1
'Start by setting a flag to immediately stop checking
'if a cell is NOT blank and initializing the column counter
blnAllBlank = True
lngColCounter = 2
'Check cells from left to right while the flag is True
'and the we are within the farthest-right column
While blnAllBlank And lngColCounter <= lngLastCol
'If the cell is NOT blank, trip the flag and exit the loop
If .Cells(lngIdx, lngColCounter) <> "" Then
blnAllBlank = False
Else
lngColCounter = lngColCounter + 1
End If
Wend
'Delete the row if the blnBlank variable is True
If blnAllBlank Then
.rows(lngIdx).delete
End If
Next lngIdx
End With
MsgBox "Blank rows have been deleted."
End Sub
This was sourced from this website and then slightly adapted to allow the user to choose which worksheet they want to empty rows removed from.
answered Dec 18, 2017 at 21:50
RugsKidRugsKid
3247 silver badges25 bronze badges
In order to have the On Error Resume function work you must declare the workbook and worksheet values as such
On Error Resume Next
ActiveWorkbook.Worksheets("Sheet Name").Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
On Error GoTo 0
I had the same issue and this eliminated all the empty rows without the need to implement a For loop.
answered Apr 30, 2018 at 14:39
This worked great for me (you can adjust lastrow and lastcol as needed):
Sub delete_rows_blank2()
t = 1
lastrow = ActiveSheet.UsedRange.Rows.Count
lastcol = ActiveSheet.UsedRange.Columns.Count
Do Until t = lastrow
For j = 1 To lastcol
'This only checks the first column because the "Else" statement below will skip to the next row if the first column has content.
If Cells(t, j) = "" Then
j = j + 1
If j = lastcol Then
Rows(t).Delete
t = t + 1
End If
Else
'Note that doing this row skip, may prevent user from checking other columns for blanks.
t = t + 1
End If
Next
Loop
End Sub
answered Feb 27, 2018 at 15:10
Here is the quickest way to Delete all blank Rows ( based on one Columns )
Dim lstRow as integet, ws as worksheet
Set ws = ThisWorkbook.Sheets("NameOfSheet")
With ws
lstRow = .Cells(Rows.Count, "B").End(xlUp).Row ' Or Rows.Count "B", "C" or "A" depends
.Range("A1:E" & lstRow).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End with
answered Mar 10, 2022 at 15:46
Your macro does what you intend, but in a very confusing manner.
Whilst running, you’re not actually analysing the currentRow
but the currentRow + 1
. For something like that I’d prefer a name like baseRow
because it implies that other calculations will be done on top of it. In any case, it would be much simpler to just go last-row to first and avoid all the line-numbering messiness.
IMO, if you have a macro called RemoveEmptyLines
(presumably attached to some descriptively-named Button) then asking the user to confirm that is what they want to do is unnecessary and probably annoying to the User-Experience.
I’m also not a fan of using worksheet functions in VBA, especially when used to determine the current state of the worksheet. Excel is notoriously unreliable at maintaining an accurate up-to-date version of things like usedRange
, lastCell
etc.
If you want to know the final row across all 10,000-odd columns then you’re kinda stuck with it, but I think that’s overkill. If somebody sends you a spreadsheet of data, there should be at least one column somewhere which contains data for every row. Might be names, might be ID/Reference numbers, might be dates etc.
I would structure your sub as a procedure that takes a column reference as an argument, or asks the user to input it, then uses that column for the basis of determining your finalRow.
You should also avoid multiple delete actions. It’s fine for small worksheets, but try deleting a row in a worksheet with lots of data and it can take a long time, each time. Instead, I would create a range, name it deleteRange
and use Union()
to add any new «rows to be deleted» to it. Then, you can have just one delete action at the end of your sub and do it all in one go.
Your sub then looks like this:
Option Explicit
Public Sub RemoveEmptyLines()
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Dim columnReference As String
columnReference = InputBox("Please input the Letter-Reference of the key data column")
Dim columnNumber As Long
On Error Resume Next '/ Check that it is a valid reference
columnNumber = Columns(columnReference).Column
On Error GoTo 0
If Not columnNumber > 0 Then
MsgBox "Your column reference was not recognised, please try again"
Exit Sub
End If
Dim lastRow As Long, firstRow As Long, currentRow As Long
Dim lineIsEmpty As Boolean
Dim deleteRange As Range
Dim deleteCount As Long
last Row = Cells(Rows.Count, columnNumber).End(xlUp).Row
firstRow = 1
For currentRow = lastRow To firstRow Step -1
lineIsEmpty = (Cells(currentRow, Columns.Count).End(xlToLeft).Column = 1 And IsEmpty(Cells(currentRow, 1)) And IsEmpty(Cells(currentRow, Columns.Count)))
If lineIsEmpty Then
If deleteRange Is Nothing Then Set deleteRange = Cells(currentRow, 1) Else Set deleteRange = Union(deleteRange, Cells(currentRow, 1))
deleteCount = deleteCount + 1
End If
Next currentRow
If Not deleteRange Is Nothing Then deleteRange.EntireRow.Delete
MsgBox deleteCount & " rows have been deleted.", vbInformation, "Result"
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub
Succinct, clear, easy to read and understand.