Метод Range.Clear для полной очистки диапазона ячеек из кода VBA Excel. Методы очистки отдельных свойств и их групп в ячейках. Примеры использования.
Методы очистки ячеек
Метод | Очищаемые свойства | Примечание |
---|---|---|
Range.Clear | Почти все свойства | Ширина и высота ячеек не изменяются |
Range.ClearComments | Комментарии | Для Excel в составе Office 365 |
Range.ClearContents | Формулы и значения | Исходное форматирование сохраняется |
Range.ClearFormats | Свойства, задающие форматы | В том числе отмена объединения ячеек |
Range.ClearHyperlinks | Гиперссылки | Текст и форматирование сохраняются |
Range.ClearNotes | Примечания и заметки | Примечания – для локальных программ Excel, заметки – для Excel в составе Office 365 |
Range.ClearOutline | Структура данных | Смотрите, что такое структурирование данных |
Range – выражение, возвращающее диапазон ячеек.
Примеры использования
1. Удаление гиперссылки из ячейки A1
Cells(1, 1).ClearHyperlinks
2. Очистка диапазона A1:L50 от формул и значений
Range("A1:L50").ClearContents
3. Очистка всех свойств ячеек в столбцах A:K
Columns("A:K").Clear
4. Очистка форматирования ячеек в строках 1:20
Rows("1:20").ClearFormats
Методы очистки диапазонов ячеек в VBA Excel возвращают очищаемые свойства ячеек к значениям по умолчанию. К таким, как на вновь созданном стандартном рабочем листе. При любых методах очистки высота строк и ширина столбцов не изменяются.
Фразы для контекстного поиска: очистка ячеек, очистка ячейки, очистка формул, очистка от формул, удаление формул, очистка значений, удаление значений, очистка форматов, удаление форматирования, удаление форматов.
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
hk1209 Пользователь Сообщений: 271 |
#1 30.01.2014 11:39:19 всем доброго времени суток
спасибо за потраченное драгоценное время Изменено: hk1209 — 30.01.2014 20:05:32 |
||
Hugo Пользователь Сообщений: 23253 |
Чтож Вы с строкой сравниваете дату? Или там тоже строка, а не дата? |
hk1209 Пользователь Сообщений: 271 |
|
wowick Пользователь Сообщений: 972 |
А сравниваете вы ее с ТЕКСТОМ «20.11.2013»… В экселе, как и во-многих других средах программирования в кавычках подразумевает текстовый формат. Если автоматизировать бардак, то получится автоматизированный бардак. |
Sanja Пользователь Сообщений: 14838 |
#5 30.01.2014 11:51:07 Попробуйте так
Согласие есть продукт при полном непротивлении сторон. |
||
Hugo Пользователь Сообщений: 23253 |
То что там дата — это ещё не факт. Видали мы всяких дат… Пока не докажете — не поверю |
hk1209 Пользователь Сообщений: 271 |
#7 30.01.2014 12:32:37 Sanja спасибо за подсказку
долго выполняется |
||
Sanja Пользователь Сообщений: 14838 |
#8 30.01.2014 12:44:02 Для ускорения выполнения кода отключите автоматический пересчет:
в конце процедуры включить:
так определяется
номер последней строки с данными в 9-м столбце:
Изменено: Sanja — 30.01.2014 12:45:13 Согласие есть продукт при полном непротивлении сторон. |
||||||
Hugo Пользователь Сообщений: 23253 |
4. Обрабатывать массивы, а не ячейки — на листе только удалять строки, да и тут можно это делать один раз сразу с группой. P.S.Упустил — Dim rw As Date — это ошибка! Изменено: Hugo — 30.01.2014 12:57:32 |
hk1209 Пользователь Сообщений: 271 |
#10 30.01.2014 13:52:19 Sanja & Hugo спасибо за подсказку и потраченное драгоценное время
Знаю что там не правильно, но не могу понять где именно Изменено: hk1209 — 30.01.2014 20:06:26 |
||
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
#11 30.01.2014 14:02:46 Cells(Rows.Count, 9).End(xlUp).Row < CDate(«20.11.2013») Hugo совсем иное советовал..
И уже в цикле:
С массивами чуть сложнее в понимании, но на Вашем примере было бы так:
P.S. И оформляйте коды тегами. Значок «<…>» среди кнопок вверху при создании сообщения. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||||
Hugo Пользователь Сообщений: 23253 |
Супербыстрое удаление строк от ZVI есть тут: http://www.sql.ru/forum/actualthread.aspx?tid=722758 Можно использовать и в этой задаче. |
hk1209 Пользователь Сообщений: 271 |
#13 30.01.2014 14:24:29 The_Prist спасибо за потраченное драгоценное время и советы (включая код) |
You need to test that there are any blanks.
If WorksheetFunction.CountBlank(Worksheet.Columns("A:A")) > 0 Then
Worksheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
You can just use On Error Resume Next to skip over the line if there are no blanks, but it’s generally preferable to test for a specific condition, rather than assuming you know what the error will be.
As far as I can see you’d only get the «No Cells Found» message if every cell in Column A has a value.
EDIT: Based on @brettdj’s comments, here’s an alternative that still uses CountBlank:
If WorksheetFunction.CountBlank(Intersect(worksheet.UsedRange, ws.Columns("A:A"))) > 0 Then
worksheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
Of course UsedRange is notoriously fickle and may be bigger than it appears. I think it’s best to first determine the actual range where the rows are to be deleted and then check the SpecialCells in that range, e.g.:
Sub DeleteRows()
Dim ws As Excel.Worksheet
Dim LastRow As Long
Set ws = ActiveSheet
LastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
With ws.Range("A2:A" & LastRow)
If WorksheetFunction.CountBlank(.Cells) > 0 Then
.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
End With
End Sub
One last note — I changed the variable from «worksheet» to «ws» as «worksheet» is an Excel reserved word.