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
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 спасибо за потраченное драгоценное время и советы (включая код) |
In this VBA Tutorial, you learn how to use Excel VBA to delete rows based on a variety of criteria.
This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.
Use the following Table of Contents to navigate to the section you’re interested in.
Related VBA and Macro Tutorials
The following VBA and Macro Tutorials may help you better understand and implement the contents below.
- General VBA constructs and structures:
- Learn about using variables here.
- Learn about VBA data types here.
- Learn about R1C1 style-references here.
- Learn about using worksheet functions in VBA here.
- Practical VBA applications and macro examples:
- Learn how to work with worksheets here.
- Learn how to insert rows here.
- Learn how to delete columns here.
- Learn how to find the last column in a worksheet here.
You can find additional VBA and Macro Tutorials in the Archives.
VBA Code to Delete a Row
To delete a row using VBA, use a statement with the following structure:
Worksheets.Rows(Row#).Delete
Process Followed by VBA Code
VBA Statement Explanation
Worksheets.Rows(Row#).Delete
- Item: Worksheets.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Rows(Row#).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing row number Row# of the worksheet returned by item #1 above.
If you explicitly declare a variable to represent Row#, use the Long data type.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #2 above.
Macro Example
The following macro deletes row 6 of the worksheet named “Delete row”.
Sub deleteRow() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Worksheets("Delete row").Rows(6).Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes row 6 of the worksheet.
#2: Delete a Row and Shift Up
VBA Code to Delete a Row and Shift Up
To delete a row and explicitly shift cells up to replace the deleted row, use a statement with the following structure:
Worksheet.Rows(Row#).Delete Shift:=xlShiftUp
Process Followed by VBA Code
VBA Statement Explanation
Worksheet.Rows(Row#).Delete Shift:=xlShiftUp
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Rows(Row#).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing row number Row# of the worksheet returned by item #1 above.
If you explicitly declare a variable to represent Row#, use the Long data type.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #2 above.
- Item: Shift:=xlShiftUp.
- VBA Construct: Shift parameter of the Range.Delete method.
- Description:
- Shifts rows up (xlShiftUp) to replace the deleted row.
- You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When deleting a row, this generally results in Excel shifting the cells up.
Macro Example
The following macro deletes row 10 of the worksheet named “Delete row” and explicitly specifies to shift cells up to replace the deleted row.
Sub deleteRowShiftUp() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Worksheets("Delete row").Rows(10).Delete Shift:=xlShiftUp End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes row 10 of the worksheet and shifts cells up to replace the deleted row.
#3: Delete Multiple Rows
VBA Code to Delete Multiple Rows
To delete multiple rows, use a statement with the following structure:
Worksheet.Rows("FirstRow#:LastRow#").Delete
Process Followed by VBA Code
VBA Statement Explanation
Worksheet.Rows(“FirstRow#:LastRow#”).Delete
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Rows(“FirstRow#:LastRow#”).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing rows number FirstRow# through LastRow# of the worksheet returned by item #1 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #2 above.
Macro Example
The following macro deletes rows 14 to 18 of the worksheet named “Delete row”.
Sub deleteMultipleRows() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Worksheets("Delete row").Rows("14:18").Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes rows 14 to 18 of the worksheet.
#4: Delete Selected Row
VBA Code to Delete Selected Row
To delete the selected row (the row containing the active cell), use the following statement:
ActiveCell.EntireRow.Delete
Process Followed by VBA Code
VBA Statement Explanation
ActiveCell.EntireRow.Delete
- Item: ActiveCell.
- VBA Construct: Application.ActiveCell property.
- Description: Returns a Range object representing the active cell.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire row containing the cell range returned by item #1 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #2 above.
Macro Example
The following macro deletes the selected row (the row containing the active cell):
Sub deleteSelectedRow() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ ActiveCell.EntireRow.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. When I execute the macro, the active cell is B20. As expected, Excel deletes the selected row.
#5: Delete Multiple Selected Rows
VBA Code to Delete Multiple Selected Rows
To delete multiple selected rows, use the following statement:
Selection.EntireRow.Delete
Process Followed by VBA Code
VBA Statement Explanation
Selection.EntireRow.Delete
- Item: Selection.
- VBA Construct: Application.Selection property.
- Description: Returns a Range object representing the current cell range selection.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire row containing the Range object returned by item #1 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #2 above.
Macro Example
The following macro deletes the (multiple) selected rows.
Sub deleteSelectedRows() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Selection.EntireRow.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. When I execute the macro, the selected cells are B24 to B28. As expected, Excel deletes the selected rows.
#6: Delete Blank Rows
VBA Code to Delete Blank Rows
To delete blank rows, use a macro with the following statement structure:
With Worksheet For Counter = LastRow To FirstRow Step -1 If WorksheetFunction.CountA(.Rows(Counter)) = 0 Then If Not BlankRows Is Nothing Then Set BlankRows = Union(BlankRows, .Rows(Counter)) Else Set BlankRows = .Rows(Counter) End If End If Next Counter End With If Not BlankRows Is Nothing Then BlankRows.Delete
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #11: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #2 through #10 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Lines #2 and #10: For Counter = LastRow To FirstRow Step -1 | Next Counter
- Item: For… Next Counter.
- VBA Construct: For… Next statement.
- Description: Repeats the statements within the loop (lines #3 through #9 below) for each row between (and including) FirstRow (item #4 below) and LastRow (item #3 below).
- Item: Counter.
- VBA Construct: Counter of For… Next statement.
- Description: Loop counter. If you explicitly declare a variable to represent the loop counter, use the Long data type.
- Item: LastRow.
- VBA Construct: Counter Start of For… Next statement.
- Description: Number of the last row (further down the worksheet) you want the macro to consider when identifying blank rows. The number of the last row is also the initial value of Counter (item #2 above).
If you explicitly declare a variable to represent the number of the last row to consider, use the Long data type.
- Item: FirstRow.
- VBA Construct: Counter End of For… Next statement.
- Description: Number of the first row (closer to the top of the worksheet) you want the macro to consider when identifying blank rows. The number of the first row is also the final value of Counter (item (#2 above).
If you explicitly declare a variable to represent the number of the first row to consider, use the Long data type.
- Item: Step -1.
- VBA Construct: Step of For… Next statement.
- Description: Amount by which Counter (item #2 above) changes every time a loop iteration occurs.
In this scenario, you loop backwards: from LastRow (item #3 above) to FirstRow (item #4 above). Therefore, step is -1.
Line #3: If WorksheetFunction.CountA(.Rows(Counter)) = 0 Then
- Item: If… Then.
- VBA Construct: Opening line of If… Then… Else statement.
- Description: Conditionally executes the statements within the If… Then block (lines #4 through #8 below) if the condition specified by item #4 below is met.
- Item: WorksheetFunction.CountA.
- VBA Construct: WorksheetFunction.CountA method.
- Description: Counts the number of cells that aren’t empty in the range returned by item #3 below.
Since the range returned by item #3 below represents the row through which the macro is currently looping, Worksheet.CountA counts the number of cells that aren’t empty in that row.
- Item: .Rows(Counter).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing the row through which the macro is currently looping.
- Item: WorksheetFunction.CountA(.Rows(Counter)) = 0.
- VBA Construct: Condition of If… Then… Else statement.
- Description: This condition is a numeric expression that evaluates to True or False, as follows:
- True: When the WorksheetFunction.CountA method (item #2 above) returns 0. This happens when the row through which the macro is currently looping (item #3 above) is empty and, therefore, the number of non-empty cells is 0.
- False: When WorksheetFunction.CountA returns a number other than 0. This happens when the row through which the macro is currently looping isn’t empty and, therefore, the number of non-empty cells isn’t 0.
Line #4: If Not BlankRows Is Nothing Then
- Item: If… Then.
- VBA Construct: Opening line of If… Then… Else statement.
- Description: Conditionally executes the statement within the If… Then… Else block (line #5 below) if the condition specified by item #6 below is met.
- Item: Not.
- VBA Construct: Not operator.
- Description: Carries out a logical negation on item #3 below. In other words, if item #3 returns:
- True, the result is False.
- False, the result is True.
- Item: BlankRows.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the empty rows found by the macro.
- Item: Is.
- VBA Construct: Is Operator.
- Description: Compares 2 object reference variables: (i) Not BlankRows (items #2 and #3 above) vs. (ii) Nothing (item #5 below).
If both object references refer to the same object, the Is operator returns True. If they refer to different objects, Is returns False.
- Item: Nothing.
- Description: The default value for a data type. In the case of an object variable (such as BlankRows), a null reference.
- Item: Not BlankRows Is Nothing.
- VBA Construct: Condition of If… Then… Else statement.
- Description: The condition is an expression that evaluates to True or False, as follows:
- True: When “Not BlankRows” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when BlankRows is “something”.
Since BlankRows holds a Range object representing cell ranges within the empty rows found by the macro, BlankRows is something if the macro finds at least one such row.
- False: When “Not BlankRows” refers to a different object from Nothing. This happens when BlankRows itself is Nothing. This occurs prior to the macro finding the first empty row. This is because BlankRows isn’t assigned to anything prior to that moment.
- True: When “Not BlankRows” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when BlankRows is “something”.
Line #5: Set BlankRows = Union(BlankRows, .Rows(Counter))
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by item #6 below to BlankRows (item #2 below).
- Item: BlankRows.
- VBA Construct: Object (Range) variable of Set statement.
- Description:
- Holds a Range object representing the empty rows found by the macro.
- BlankRows is included twice in the statement. In the first mention (Set BlankRows), BlankRows is the object variable to which an object reference is assigned.
- Item: Union.
- VBA Construct: Application.Union method.
- Description: Returns a Range object representing the union of the Range objects returned by items #4 and #5 below.
- Item: BlankRows.
- VBA Construct: Object (Range) variable.
- Description:
- Holds a Range object representing the empty rows found by the macro.
- BlankRows is included twice in the statement. In the second mention (Union(BlankRows, .Rows(Counter)), BlankRows is one of the parameters of the Application.Union method.
- Item: .Rows(Counter).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing the row through which the macro is currently looping.
- Item: Union(BlankRows, .Rows(Counter).
- VBA Construct: Object expression of Set statement.
- Description: Returns the new Range object reference assigned to the BlankRows object variable (item #2 above). This is the union of the following 2 Range objects:
- Prior to the Set statement, BlankRows represents cell ranges within the empty rows found by the macro prior to the row through which it’s currently looping.
- “.Rows(Counter)” represents the row through which the macro is currently looping.
Graphically, this looks as follows:
In other words, any empty row the macro finds is “added” to BlankRows.
Line #6: Else
- Item: Else.
- VBA Construct: Else clause of If… Then… Else statement.
- Description: The statement following the Else clause (line #7 below) is executed if the condition tested in the opening line of the If… Then… Else statement (line #4 above) isn’t met and returns False.
Line #7: Set BlankRows = .Rows(Counter)
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by item #3 below to BlankRows (item #2 below).
- Item: BlankRows.
- VBA Construct: Object (Range) variable of Set statement.
- Description: Holds a Range object representing the empty rows found by the macro.
- Item: .Rows(Counter).
- VBA Construct: Worksheet.Rows property.
- Description: Returns a Range object representing the row through which the macro is currently looping.
Lines #8 and #9: End If | End If
- Item: End If.
- VBA Construct: Closing lines of If… Then… Else statements.
- Description: Ends the If… Then… Else statements that began in lines #3 and #4 above.
Line #12: If Not BlankRows Is Nothing Then BlankRows.Delete
- Item: If… Then.
- VBA Construct: If… Then… Else statement.
- Description: Conditionally executes the statement at the end of the line (items #7 and #8 below) if the condition specified by item #6 below is met.
- Item: Not.
- VBA Construct: Not operator.
- Description: Carries out a logical negation on item #3 below. In other words, if item #3 returns:
- True, the result is False.
- False, the result is True.
- Item: BlankRows.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the empty rows found by the macro.
- Item: Is.
- VBA Construct: Is Operator.
- Description: Compares 2 object reference variables: (i) Not BlankRows (items #2 and #3 above) vs. (ii) Nothing (item #5 below).
If both object references refer to the same object, the Is operator returns True. If they refer to different objects, Is returns False.
- Item: Nothing.
- Description: The default value for a data type. In the case of an object variable (such as BlankRows), a null reference.
- Item: Not BlankRows Is Nothing.
- VBA Construct: Condition of If… Then… Else statement.
- Description: The condition is an expression that evaluates to True or False, as follows:
- True: When “Not BlankRows” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when BlankRows is “something”.
Since BlankRows holds a Range object representing cell ranges within the empty rows found by the macro, BlankRows is something if the macro has found at least 1 empty row.
- False: When “Not BlankRows” refers to a different object from Nothing. This happens when BlankRows itself is Nothing. This, in turn, occurs when the macro founds no empty rows.
- True: When “Not BlankRows” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when BlankRows is “something”.
- Item: BlankRows.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the empty rows found by the macro.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #7 above.
Macro Example
The following macro deletes all blank rows between rows number myFirstRow and LastRow.
- myFirstRow is set to 6.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete empty rows”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
Sub deleteEmptyRows() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myWorksheet As Worksheet Dim iCounter As Long Dim myBlankRows As Range myFirstRow = 6 Set myWorksheet = Worksheets("Delete empty rows") With myWorksheet myLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row For iCounter = myLastRow To myFirstRow Step -1 If WorksheetFunction.CountA(.Rows(iCounter)) = 0 Then If Not myBlankRows Is Nothing Then Set myBlankRows = Union(myBlankRows, .Rows(iCounter)) Else Set myBlankRows = .Rows(iCounter) End If End If Next iCounter End With If Not myBlankRows Is Nothing Then myBlankRows.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes all blank rows between row 6 and the last row with data on the worksheet.
#7: Delete Rows with Blank Cells
VBA Code to Delete Rows with Blank Cells
To delete rows with blank cells using VBA, use a macro with the following statement structure:
With Worksheet Set RangeForCriteria = .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) End With On Error Resume Next RangeForCriteria.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #3: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: The statement within the With… End With statement (line #2 below) is executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Line #2: Set RangeForCriteria = .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn))
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by items #3 through #5 below to RangeForCriteria (item #2 below).
- Item: RangeForCriteria.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cell range you want the macro to search for blank cells.
- Item: .Range.
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell range specified as follows:
- Upper-left corner cell: Range object returned by item #4 below.
- Lower-right corner cell: Range object returned by item #5 below.
- Item: .Cells(FirstRow, FirstColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number FirstRow and column number FirstColumn.
FirstRow and FirstColumn are the number of, respectively, the first row and first column in the cell range you want the macro to search for blank cells. If you explicitly declare a variable to represent FirstRow or FirstColumn, use the Long data type.
- Item: .Cells(LastRow, LastColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number LastRow and column number LastColumn.
LastRow and LastColumn are the number of, respectively, the last row and last column in the cell range you want the macro to search for blank cells. If you explicitly declare a variable to represent LastRow or LastColumn, use the Long data type.
Line #4: On Error Resume Next
- Item: On Error Resume Next.
- VBA Construct: On Error Resume Next statement.
- Description: Specifies that, when a run-time error occurs, control goes to the statement following the statement where the error occurs.
The error-handler in this line #4 is necessary because, if the cell range you want the macro to search for blank cells doesn’t contain any such cells, line #5 below generates a run-time error.
Line #5: RangeForCriteria.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
- Item: RangeForCriteria.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cell range you want the macro to search for blank cells.
- Item: SpecialCells(xlCellTypeBlanks).
- VBA Construct: Range.SpecialCells method and Type parameter of Range.SpecialCells method.
- Description: Returns a Range object representing all empty cells within the cell range returned by RangeForCriteria (item #1 above).
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire rows containing the Range object returned by item #2 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #3 above.
Macro Example
The following macro deletes all rows with blank cells between:
- Rows number myFirstRow and myLastRow.
- Columns number myFirstColumn and myLastColumn.
In this example:
- myFirstRow is set to 6.
- myFirstColumn is set to 2.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete row with blank cells”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
- myLastColumn is set to the number of the last column with data in the same worksheet. The constructs used by the statement that finds the last column with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Column property.
Sub deleteRowBlankCells() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long Dim myWorksheet As Worksheet Dim myRange As Range myFirstRow = 6 myFirstColumn = 2 Set myWorksheet = Worksheets("Delete row with blank cells") With myWorksheet With .Cells myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End With Set myRange = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) End With On Error Resume Next myRange.SpecialCells(xlCellTypeBlanks).EntireRow.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes all rows with blank cells between (i) row 6 and the last row with data on the worksheet, and (ii) column 2 and the last column with data on the worksheet.
#8: Delete Rows with Blank Cells in a Specific Column
VBA Code to Delete Rows with Blank Cells in a Specific Column
To delete rows with blank cells in a specific column using VBA, use a macro with the following statement structure:
With Worksheet With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) .AutoFilter Field:=CriteriaField, Criteria1:="=" On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #8: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #2 through #7 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Lines #2 and #6: With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #3 through #6 below) are executed on the range object returned by items #2 through #4 below.
- Item: .Range.
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell range specified as follows:
- Upper-left corner cell: Range object returned by item #3 below.
- Lower-right corner cell: Range object returned by item #4 below.
- Item: .Cells(FirstRow, FirstColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number FirstRow and column number FirstColumn.
FirstRow and FirstColumn are the number of, respectively, the first row and first column in the cell range you work with. If you explicitly declare a variable to represent FirstRow or FirstColumn, use the Long data type.
- Item: .Cells(LastRow, LastColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number LastRow and column number LastColumn.
LastRow and LastColumn are the number of, respectively, the last row and last column in the cell range you work with. If you explicitly declare a variable to represent LastRow or LastColumn, use the Long data type.
Line #3: .AutoFilter Field:=CriteriaField, Criteria1:=”=”
- Item: .AutoFilter.
- VBA Construct: Range.AutoFilter method.
- Description: Filter the data within the range you work with using the AutoFilter and according to the parameters specified by items #2 and #3 below.
- Item: Field:=CriteriaField.
- VBA Construct: Field parameter of Range.AutoFilter method.
- Description: Specifies the field on which you want to base the filter. The leftmost field of the range you work with is Field 1. The rightmost field is the number of fields in the cell range you work with.
If you explicitly declare a variable to represent CriteriaField, use the Long data type.
- Item: Criteria1:=”=”.
- VBA Construct: Criteria1 parameter of Range.AutoFilter method.
- Description: Specifies the filtering criteria. “=” finds blank cells.
Line #4: On Error Resume Next
- Item: On Error Resume Next.
- VBA Construct: On Error Resume Next statement.
- Description: Specifies that, when a run-time error occurs, control goes to the statement following the statement where the error occurs.
The error-handler in this line #4 is necessary because, if the field you filter by (line #3 above) doesn’t contain blank cells, line #5 below generates a run-time error.
Line #5: .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count – 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete
- Item: Offset.
- VBA Construct: Range.Offset property.
- Description: Returns a Range object a number of rows above or below the cell range it works with, as returned by line #2 above.
- Item: RowOffset:=1.
- VBA Construct: RowOffset parameter of Range.Offset property.
- Description: Specifies that the cell range returned by Range.Offset (item #1 above) is 1 row below the range specified in line #2 above.
Line #2 above specifies the cell range you work with. Therefore, the Range object that Range.Offset returns has the same size but is 1 row below the cell range you work with. This results in the following:
- The headers of the cell range you work with are excluded from the Range object.
- The first empty row below the last row with data (LastRow in line #2 above) is included. This extra line is handled by item #7 below.
- Item: Resize.
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above.
- Item: RowSize.
- VBA Construct: RowSize parameter of Range.Resize property.
- Description: Specifies the number of rows in the new cell range returned by Range.Resize (item #3 above).
- Item: Rows.
- VBA Construct: Range.Rows property.
- Description: Returns a Range object representing the rows in the cell range it works with, as returned by line #2 above.
- Item: Count.
- VBA Construct: Range.Count property.
- Description: Returns the number of rows within the Range object returned by item #5 above.
- Item: Resize(RowSize:=(.Rows.Count – 1)).
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above to reduce it by one row. The number of rows in the new range is obtained by subtracting 1 from the number of rows returned by line #2, as counted by items #5 and #6 above.
This results in a cell range that excludes the first empty row below the last row with data that the Range.Offset property (items #1 and #2 above) included.
- Item: SpecialCells(xlCellTypeVisible).
- VBA Construct: Range.SpecialCells method and Type parameter of Range.SpecialCells method.
- Description: Returns a Range object representing all visible cells within the cell range you work with, excluding the headers (as required by item #2 above).
Since line #3 above filters the data according to the criteria you specify, the visible cells returned by Range.SpecialCells are those containing blank cells in the column (field) you specify.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire rows containing the Range object returned by item #8 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #10 above.
Line #7: .AutoFilterMode = False
- Item: .AutoFilterMode = False.
- VBA Construct: Worksheet.AutoFilterMode property.
- Description: Specifies that the AutoFilter drop-down arrows aren’t displayed on the worksheet.
Macro Example
The following macro deletes all rows that meet the following conditions:
- Are between:
- Rows number (myFirstRow + 1) and myLastrow.
- Columns number myFirstColumn and myLastColumn.
- Contain a blank cell in field number myCriteriaField.
In this example:
- myFirstRow is set to 5.
- myFirstColumn is set to 2.
- myCriteriaField is set to 1.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete row if cell is blank”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
- myLastColumn is set to the number of the last column with data in the same worksheet. The constructs used by the statement that finds the last column with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Column property.
Sub deleteRowBlankCell() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long Dim myCriteriaField As Long Dim myWorksheet As Worksheet myFirstRow = 5 myFirstColumn = 2 myCriteriaField = 1 Set myWorksheet = Worksheets("Delete row if cell is blank") With myWorksheet With .Cells myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End With With .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) .AutoFilter Field:=myCriteriaField, Criteria1:="=" On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes the rows containing blank cells in myCriteriaField (1).
#9: Delete Rows Containing Strings
VBA Code to Delete Rows Containing Strings
To delete rows containing strings using VBA, use a macro with the following statement structure:
With Worksheet Set RangeForCriteria = .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) End With On Error Resume Next RangeForCriteria.SpecialCells(xlCellTypeConstants, xlTextValues).EntireRow.Delete
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #3: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: The statement within the With… End With statement (line #2 below) is executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Line #2: Set RangeForCriteria = .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn))
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by items #3 through #5 below to RangeForCriteria (item #2 below).
- Item: RangeForCriteria.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cell range you want the macro to search for cells containing strings.
- Item: .Range.
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell range specified as follows:
- Upper-left corner cell: Range object returned by item #4 below.
- Lower-right corner cell: Range object returned by item #5 below.
- Item: .Cells(FirstRow, FirstColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number FirstRow and column number FirstColumn.
FirstRow and FirstColumn are the number of, respectively, the first row and first column in the cell range you want the macro to search for cells containing strings. If you explicitly declare a variable to represent FirstRow or FirstColumn, use the Long data type.
- Item: .Cells(LastRow, LastColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number LastRow and column number LastColumn.
LastRow and LastColumn are the number of, respectively, the last row and last column in the cell range you want the macro to search for cells containing strings. If you explicitly declare a variable to represent LastRow or LastColumn, use the Long data type.
Line #4: On Error Resume Next
- Item: On Error Resume Next.
- VBA Construct: On Error Resume Next statement.
- Description: Specifies that, when a run-time error occurs, control goes to the statement following the statement where the error occurs.
The error-handler in this line #4 is necessary because, if the cell range you want the macro to search for cells containing strings doesn’t contain any such cells, line #5 below generates a run-time error.
Line #5: RangeForCriteria.SpecialCells(xlCellTypeConstants, xlTextValues).EntireRow.Delete
- Item: RangeForCriteria.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cell range you want the macro to search for cells containing strings.
- Item: SpecialCells(xlCellTypeConstants, xlTextValues).
- VBA Construct: Range.SpecialCells method, Type and Value parameters of Range.SpecialCells method.
- Description: Returns a Range object representing all cells containing constant (xlCellTypeConstants) text values (xlTextValues) within the cell range returned by RangeForCriteria (item #1 above). Those are the cells containing strings.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire rows containing the Range object returned by item #2 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #3 above.
Macro Example
The following macro deletes all rows containing strings between:
- Rows number myFirstRow and myLastRow.
- Columns number myFirstColumn and myLastColumn.
In this example:
- myFirstRow is set to 6.
- myFirstColumn is set to 2.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete rows containing strings”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
- myLastColumn is set to the number of the last column with data in the same worksheet. The constructs used by the statement that finds the last column with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Column property.
Sub deleteRowContainingStrings() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long Dim myWorksheet As Worksheet Dim myRange As Range myFirstRow = 6 myFirstColumn = 2 Set myWorksheet = Worksheets("Delete rows containing strings") With myWorksheet With .Cells myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End With Set myRange = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) End With On Error Resume Next myRange.SpecialCells(xlCellTypeConstants, xlTextValues).EntireRow.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes all rows containing strings between (i) row 6 and the last row with data on the worksheet, and (ii) column 2 and the last column with data on the worksheet.
#10: Delete Row Based on Cell Value
VBA Code to Delete Row Based on Cell Value
To delete rows based on the value in a specific cell using VBA, use a macro with the following statement structure:
With Worksheet With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) .AutoFilter Field:=CriteriaField, Criteria1:=Value On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #8: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #2 through #7 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Lines #2 and #6: With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #3 through #6 below) are executed on the range object returned by items #2 through #4 below.
- Item: .Range.
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell range specified as follows:
- Upper-left corner cell: Range object returned by item #3 below.
- Lower-right corner cell: Range object returned by item #4 below.
- Item: .Cells(FirstRow, FirstColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number FirstRow and column number FirstColumn.
FirstRow and FirstColumn are the number of, respectively, the first row and first column in the cell range you work with. If you explicitly declare a variable to represent FirstRow or FirstColumn, use the Long data type.
- Item: .Cells(LastRow, LastColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number LastRow and column number LastColumn.
LastRow and LastColumn are the number of, respectively, the last row and last column in the cell range you work with. If you explicitly declare a variable to represent LastRow or LastColumn, use the Long data type.
Line #3: .AutoFilter Field:=CriteriaField, Criteria1:=Value
- Item: .AutoFilter.
- VBA Construct: Range.AutoFilter method.
- Description: Filter the data within the range you work with using the AutoFilter and according to the parameters specified by items #2 and #3 below.
- Item: Field:=CriteriaField.
- VBA Construct: Field parameter of Range.AutoFilter method.
- Description: Specifies the field on which you want to base the filter. The leftmost field of the range you work with is Field 1. The rightmost field is the number of fields in the cell range you work with.
If you explicitly declare a variable to represent CriteriaField, use the Long data type.
- Item: Criteria1:=Value.
- VBA Construct: Criteria1 parameter of Range.AutoFilter method.
- Description: Specifies the filtering criteria. If you explicitly declare a variable to represent Value, ensure that the data type you use can handle the value you use as criteria.
Line #4: On Error Resume Next
- Item: On Error Resume Next.
- VBA Construct: On Error Resume Next statement.
- Description: Specifies that, when a run-time error occurs, control goes to the statement following the statement where the error occurs.
The error-handler in this line #4 is necessary because, if the field you filter by (line #3 above) doesn’t contain cells with the value you use as criteria, line #5 below generates a run-time error.
Line #5: .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count – 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete
- Item: Offset.
- VBA Construct: Range.Offset property.
- Description: Returns a Range object a number of rows above or below the cell range it works with, as returned by line #2 above.
- Item: RowOffset:=1.
- VBA Construct: RowOffset parameter of Range.Offset property.
- Description: Specifies that the cell range returned by Range.Offset (item #1 above) is 1 row below the range specified in line #2 above.
Line #2 above specifies the cell range you work with. Therefore, the Range object that Range.Offset returns has the same size but is 1 row below the cell range you work with. This results in the following:
- The headers of the cell range you work with are excluded from the Range object.
- The first empty row below the last row with data (LastRow in line #2 above) is included. This extra line is handled by item #7 below.
- Item: Resize.
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above.
- Item: RowSize.
- VBA Construct: RowSize parameter of Range.Resize property.
- Description: Specifies the number of rows in the new cell range returned by Range.Resize (item #3 above).
- Item: Rows.
- VBA Construct: Range.Rows property.
- Description: Returns a Range object representing the rows in the cell range it works with, as returned by line #2 above.
- Item: Count.
- VBA Construct: Range.Count property.
- Description: Returns the number of rows within the Range object returned by item #5 above.
- Item: Resize(RowSize:=(.Rows.Count – 1)).
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above to reduce it by one row. The number of rows in the new range is obtained by subtracting 1 from the number of rows returned by line #2, as counted by items #5 and #6 above.
This results in a cell range that excludes the first empty row below the last row with data that the Range.Offset property (items #1 and #2 above) included.
- Item: SpecialCells(xlCellTypeVisible).
- VBA Construct: Range.SpecialCells method and Type parameter of Range.SpecialCells method.
- Description: Returns a Range object representing all visible cells within the cell range you work with, excluding the headers (as required by item #2 above).
Since line #3 above filters the data according to the criteria you specify, the visible cells returned by Range.SpecialCells are those containing the value you’re looking for in the column (field) you specify.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire rows containing the Range object returned by item #8 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #10 above.
Line #7: .AutoFilterMode = False
- Item: .AutoFilterMode = False.
- VBA Construct: Worksheet.AutoFilterMode property.
- Description: Specifies that the AutoFilter drop-down arrows aren’t displayed on the worksheet.
Macro Example
The following macro deletes all rows that meet the following conditions:
- Are between:
- Rows number (myFirstRow + 1) and myLastRow.
- Columns number myFirstColumn and myLastColumn.
- Contain the value myValue in field number myCriteriaField.
In this example:
- myFirstRow is set to 5.
- myFirstColumn is set to 2.
- myCriteriaField is set to 1.
- myValue is set to 5.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete row based on value”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
- myLastColumn is set to the number of the last column with data in the same worksheet. The constructs used by the statement that finds the last column with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Column property.
Sub deleteRowBasedOnValue() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long Dim myCriteriaField As Long Dim myValue As Double Dim myWorksheet As Worksheet myFirstRow = 5 myFirstColumn = 2 myCriteriaField = 1 myValue = 5 Set myWorksheet = Worksheets("Delete row based on value") With myWorksheet With .Cells myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End With With .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) .AutoFilter Field:=myCriteriaField, Criteria1:=myValue On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes the rows containing myValue (5) in myCriteriaField (1).
#11: Delete Row Based on Date
VBA Code to Delete Row Based on Date
To delete rows based on the date in a specific cell using VBA, use a macro with the following statement structure:
With Worksheet For Counter = LastRow To FirstRow Step -1 With .Cells(Counter, CriteriaColumn) If .Value = Date Then If Not RowsWithDate Is Nothing Then Set RowsWithDate = Union(RowsWithDate, .Cells) Else Set RowsWithDate = .Cells End If End If End With Next Counter End With If Not RowsWithDate Is Nothing Then RowsWithDate.EntireRow.Delete
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #13: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #2 through #12 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Lines #2 and #12: For Counter = LastRow To FirstRow Step -1 | Next Counter
- Item: For… Next Counter.
- VBA Construct: For… Next statement.
- Description: Repeats the statements within the loop (lines #3 through #11 below) for each row between (and including FirstRow (item #4 below) and LastRow (item #3 below).
- Item: Counter.
- VBA Construct: Counter of For… Next statement.
- Description: Loop counter. If you explicitly declare a variable to represent the loop counter, use the Long data type.
- Item: LastRow.
- VBA Construct: Counter Start of For… Next statement.
- Description: Number of the last row (further down the worksheet) you want the macro to consider when identifying blank rows. The number of the last row is also the initial value of Counter (item #2 above).
If you explicitly declare a variable to represent the number of the last row to consider, use the Long data type.
- Item: FirstRow.
- VBA Construct: Counter End of For… Next statement.
- Description: Number of the first row (closer to the top of the worksheet) you want the macro to consider when identifying blank rows. The number of the first row is also the final value of Counter (item (#2 above).
If you explicitly declare a variable to represent the number of the first row to consider, use the Long data type.
- Item: Step -1.
- VBA Construct: Step of For… Next statement.
- Description: Amount by which Counter (item #2 above) changes every time a loop iteration occurs.
In this scenario, you loop backwards: from LastRow (item #3 above) to FirstRow (item #4 above). Therefore, step is -1.
Lines #3 and #11: With .Cells(Counter, CriteriaColumn) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #4 through #10 below) are executed on the cell returned by item #2 below.
- Item: .Cells(Counter, CriteriaColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number Counter and column number CriteriaColumn.
At any given time, the value of the loop counter (Counter) is the same as that of the row through which the macro is currently looping. CriteriaColumn is the number of the column containing the cells with dates you consider.
Line #4: If .Value = Date Then
- Item: If… Then.
- VBA Construct: Opening line of If… Then… Else statement.
- Description: Conditionally executes the statements within the If… Then block (lines #5 through #9 below) if the condition specified by item #3 below is met.
- Item: .Value.
- VBA Construct: Range.Value property.
- Description: Returns the value of the cell represented by the Range object returned by line #3 above (.Cells(Counter, CriteriaColumn)). This is the value of the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider.
- Item: .Value = Date.
- VBA Construct: Condition of If… Then… Else statement.
- Description: This condition is a numeric expression that evaluates to True or False, as follows:
- True: When the value of the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider is equal to the date you specify (Date).
- False: When the value of the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider isn’t equal to the date you specify (Date).
If you explicitly declare a variable to represent Date, ensure that the data type you use can handle the value you use as criteria. Consider, for example, using the Date data type.
When specifying the date you use as criteria, ensure that you specify the date as a value as required by VBA. For these purposes, you can use VBA constructs such as the DateValue or DateSerial Functions.
Line #5: If Not RowsWithDate Is Nothing Then
- Item: If… Then.
- VBA Construct: Opening line of If… Then… Else statement.
- Description: Conditionally executes the statement within the If… Then… Else block (line #6 below) if the condition specified by item #6 below is met.
- Item: Not.
- VBA Construct: Not operator.
- Description: Carries out a logical negation on item #3 below. In other words, if item #3 returns:
- True, the result is False.
- False, the result is True.
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- Item: Is.
- VBA Construct: Is Operator.
- Description: Compares 2 object reference variables: (i) Not RowsWithDate (items #2 and #3 above) vs. (ii) Nothing (item #5 below).
If both object references refer to the same object, the Is operator returns True. If they refer to different objects, Is returns False.
- Item: Nothing.
- Description: The default value for a data type. In the case of an object variable (such as RowsWithDate), a null reference.
- Item: Not RowsWithDate Is Nothing.
- VBA Construct: Condition of If… Then… Else statement.
- Description: The condition is an expression that evaluates to True or False, as follows:
- True: When “Not RowsWithDate” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when RowsWithDate is “something”.
Since RowsWithDate holds a Range object representing the cells with the criteria date found by the macro in a specific column (CriteriaColumn in line #3 above), RowsWithDate is something after the macro finds the first such cell.
- False: When “Not RowsWithDate” refers to a different object from Nothing. This happens when RowsWithDate itself is Nothing. This occurs prior to the macro finding the first cell with the criteria date. This is because RowsWithDate isn’t assigned to anything prior to that moment.
- True: When “Not RowsWithDate” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when RowsWithDate is “something”.
Line #6: Set RowsWithDate = Union(RowsWithDate, .Cells)
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by item #6 below to RowsWithDate (item #2 below).
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable of Set statement.
- Description:
- Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- RowsWithDate is included twice in the statement. In the first mention (Set RowsWithDate), RowsWithDate is the object variable to which an object reference is assigned.
- Item: Union.
- VBA Construct: Application.Union method.
- Description: Returns a Range object representing the union of the Range objects returned by items #4 and #5 below.
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable.
- Description:
- Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- RowsWithDate is included twice in the statement. In the second mention (Union(RowsWithDate, .Cells), RowsWithDate is one of the parameters of the Application.Union method.
- Item: .Cells.
- VBA Construct: Range.Cells property.
- Description: Returns a Range object representing the cell represented by the Range object returned by line #3 above (.Cells(Counter, CriteriaColumn)). This is the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider.
- Item: Union(RowsWithDate, .Cells).
- VBA Construct: Object expression of Set statement.
- Description: Returns the new Range object reference assigned to the RowsWithDate object variable (item #2 above). This is the union of the following 2 Range objects:
- Prior to the Set statement, RowsWithDate represents cells in the column you specify containing the date you use as criteria found by the macro prior to the row through which it’s currently looping.
- “.Cells” represents the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider.
Graphically, this looks as follows:
In other words, any cell containing the criteria date the macro finds is “added” to RowsWithDate.
Line #7: Else
- Item: Else.
- VBA Construct: Else clause of If… Then… Else statement.
- Description: The statement following the Else clause (line #8 below) is executed if the condition tested in the opening line of the If… Then… Else statement (line #5 above) isn’t met and returns False.
Line #8: Set RowsWithDate = .Cells
- Item: Set… =.
- VBA Construct: Set statement.
- Description: Assigns the object reference returned by item #3 below to RowsWithDate (item #2 below).
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable of Set statement.
- Description: Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- Item: .Cells.
- VBA Construct: Range.Cells property.
- Description: Returns a Range object representing the cell represented by the Range object returned by line #3 above (.Cells(Counter, CriteriaColumn)). This is the cell at the intersection of the row through which the macro is currently looping and the column containing the cells with dates you consider.
Lines #9 and #10: End If | End If
- Item: End If.
- VBA Construct: Closing lines of If… Then… Else statements.
- Description: Ends the If… Then… Else statements that began in lines #4 and #5 above.
Line #14: If Not RowsWithDate Is Nothing Then RowsWithDate.EntireRow.Delete
- Item: If… Then.
- VBA Construct: If… Then… Else statement.
- Description: Conditionally executes the statement within at the end of the line (items #7 through #9 below) if the condition specified by item #6 below is met.
- Item: Not.
- VBA Construct: Not operator.
- Description: Carries out a logical negation on item #3 below. In other words, if item #3 returns:
- True, the result is False.
- False, the result is True.
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- Item: Is.
- VBA Construct: Is Operator.
- Description: Compares 2 object reference variables: (i) Not RowsWithDate (items #2 and #3 above) vs. (ii) Nothing (item #5 below).
If both object references refer to the same object, the Is operator returns True. If they refer to different objects, Is returns False.
- Item: Nothing.
- Description: The default value for a data type. In the case of an object variable (such as RowsWithDate), a null reference.
- Item: Not RowsWithDate Is Nothing.
- VBA Construct: Condition of If… Then… Else statement.
- Description: The condition is an expression that evaluates to True or False, as follows:
- True: When “Not RowsWithDate” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when RowsWithDate is “something”.
Since RowsWithDate holds a Range object representing the cells with the criteria date found by the macro in a specific column (CriteriaColumn in line #3 above), RowsWithDate is something if the macro finds at least one such cell.
- False: When “Not RowsWithDate” refers to a different object from Nothing. This happens when RowsWithDate itself is Nothing. This, in turn, occurs when the macro founds no cells with the criteria date within the specified column.
- True: When “Not RowsWithDate” (items #2 and #3 above) refers to the same object as Nothing (item #5 above). This happens when RowsWithDate is “something”.
- Item: RowsWithDate.
- VBA Construct: Object (Range) variable.
- Description: Holds a Range object representing the cells in the column you specify (CriteriaColumn in line #3 above) containing the date you use as criteria.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire row containing the cell range returned by item #7 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #8 above.
Macro Example
The following macro deletes all rows that meet the following conditions:
- Are between rows number myFirstRow and myLastRow.
- Contain the date myDate in column number myCriteriaColumn.
In this example:
- myFirstRow is set to 5.
- myDate is set to the serial number representing June 15, 2017. For purposes of obtaining the appropriate serial number, I use the DateValue Function.
- myCriteriaColumn is set to 2.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete row based on date”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
Sub deleteRowBasedOnDate() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myCriteriaColumn As Long Dim myDate As Date Dim myWorksheet As Worksheet Dim iCounter As Long Dim myRowsWithDate As Range myFirstRow = 6 myCriteriaColumn = 2 myDate = DateValue("June 15, 2017") Set myWorksheet = Worksheets("Delete row based on date") With myWorksheet myLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row For iCounter = myLastRow To myFirstRow Step -1 With .Cells(iCounter, myCriteriaColumn) If .Value = myDate Then If Not myRowsWithDate Is Nothing Then Set myRowsWithDate = Union(myRowsWithDate, .Cells) Else Set myRowsWithDate = .Cells End If End If End With Next iCounter End With If Not myRowsWithDate Is Nothing Then myRowsWithDate.EntireRow.Delete End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes the rows containing myDate (June 15, 2017) in myCriteriaColumn (2).
#12: Delete Row Based on String Criteria
VBA Code to Delete Row Based on String Criteria
To delete rows based on the string in a specific cell using VBA, use a macro with the following statement structure:
With Worksheet With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) .AutoFilter Field:=CriteriaField, Criteria1:=String On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With
Process Followed by VBA Code
VBA Statement Explanation
Lines #1 and #8: With Worksheet | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #2 through #7 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
Lines #2 and #6: With .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn)) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #3 through #6 below) are executed on the range object returned by items #2 through #4 below.
- Item: .Range.
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell range specified as follows:
- Upper-left corner cell: Range object returned by item #3 below.
- Lower-right corner cell: Range object returned by item #4 below.
- Item: .Cells(FirstRow, FirstColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number FirstRow and column number FirstColumn.
FirstRow and FirstColumn are the number of, respectively, the first row and first column in the cell range you work with. If you explicitly declare a variable to represent FirstRow or FirstColumn, use the Long data type.
- Item: .Cells(LastRow, LastColumn).
- VBA Construct: Worksheet.Cells property and Range.Item property.
- Description: Returns a Range object representing the cell at the intersection of row number LastRow and column number LastColumn.
LastRow and LastColumn are the number of, respectively, the last row and last column in the cell range you work with. If you explicitly declare a variable to represent LastRow or LastColumn, use the Long data type.
Line #3: .AutoFilter Field:=CriteriaField, Criteria1:=String
- Item: .AutoFilter.
- VBA Construct: Range.AutoFilter method.
- Description: Filter the data within the range you work with using the AutoFilter and according to the parameters specified by items #2 and #3 below.
- Item: Field:=CriteriaField.
- VBA Construct: Field parameter of Range.AutoFilter method.
- Description: Specifies the field on which you want to base the filter. The leftmost field of the range you work with is Field 1. The rightmost field is the number of fields in the cell range you work with.
If you explicitly declare a variable to represent CriteriaField, use the Long data type.
- Item: Criteria1:=String.
- VBA Construct: Criteria1 parameter of Range.AutoFilter method.
- Description: Specifies the filtering criteria. If you explicitly declare a variable to represent String, use the String data type.
Line #4: On Error Resume Next
- Item: On Error Resume Next.
- VBA Construct: On Error Resume Next statement.
- Description: Specifies that, when a run-time error occurs, control goes to the statement following the statement where the error occurs.
The error-handler in this line #4 is necessary because, if the field you filter by (line #3 above) doesn’t contain cells with the string you use as criteria, line #5 below generates a run-time error.
Line #5: .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count – 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete
- Item: Offset.
- VBA Construct: Range.Offset property.
- Description: Returns a Range object a number of rows above or below the cell range it works with, as returned by line #2 above.
- Item: RowOffset:=1.
- VBA Construct: RowOffset parameter of Range.Offset property.
- Description: Specifies that the cell range returned by Range.Offset (item #1 above) is 1 row below the range specified in line #2 above.
Line #2 above specifies the cell range you work with. Therefore, the Range object that Range.Offset returns has the same size but is 1 row below the cell range you work with. This results in the following:
- The headers of the cell range you work with are excluded from the Range object.
- The first empty row below the last row with data (LastRow in line #2 above) is included. This extra line is handled by item #7 below.
- Item: Resize.
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above.
- Item: RowSize.
- VBA Construct: RowSize parameter of Range.Resize property.
- Description: Specifies the number of rows in the new cell range returned by Range.Resize (item #3 above).
- Item: Rows.
- VBA Construct: Range.Rows property.
- Description: Returns a Range object representing the rows in the cell range it works with, as returned by line #2 above.
- Item: Count.
- VBA Construct: Range.Count property.
- Description: Returns the number of rows within the Range object returned by item #5 above.
- Item: Resize(RowSize:=(.Rows.Count – 1)).
- VBA Construct: Range.Resize property.
- Description: Resizes the cell range returned by items #1 and #2 above to reduce it by one row. The number of rows in the new range is obtained by subtracting 1 from the number of rows returned by line #2, as counted by items #5 and #6 above.
This results in a cell range that excludes the first empty row below the last row with data that the Range.Offset property (items #1 and #2 above) included.
- Item: SpecialCells(xlCellTypeVisible).
- VBA Construct: Range.SpecialCells method and Type parameter of Range.SpecialCells method.
- Description: Returns a Range object representing all visible cells within the cell range you work with, excluding the headers (as required by item #2 above).
Since line #3 above filters the data according to the criteria you specify, the visible cells returned by Range.SpecialCells are those containing the string you’re looking for in the column (field) you specify.
- Item: EntireRow.
- VBA Construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire rows containing the Range object returned by item #8 above.
- Item: Delete.
- VBA Construct: Range.Delete method.
- Description: Deletes the Range object returned by item #10 above.
Line #7: .AutoFilterMode = False
- Item: .AutoFilterMode = False.
- VBA Construct: Worksheet.AutoFilterMode property.
- Description: Specifies that the AutoFilter drop-down arrows aren’t displayed on the worksheet.
Macro Example
The following macro deletes all rows that meet the following conditions:
- Are between:
- Rows number (myFirstRow + 1) and myLastRow.
- Columns number myFirstColumn and myLastColumn.
- Contain the string myString in field number myCriteriaField.
In this example:
- myFirstRow is set to 5.
- myFirstColumn is set to 2.
- myCriteriaField is set to 1.
- myString is set to “*to delete*”.
The asterisks at the beginning and end of the string act as wildcards representing any number of characters. Therefore, myString includes any strings that contain “to delete”, regardless of the text before or after it.
For example, in the example below, I use this macro to delete rows where the cell in the first column contains the string “Rows to delete now”. “to delete” is between the strings “Rows ” and ” now”, both of which are covered by the asterisk wildcard.
- myLastRow is set to the number of the last row with data in the worksheet named “Delete row based on string”. The constructs used by the statement that finds the last row with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Row property.
- myLastColumn is set to the number of the last column with data in the same worksheet. The constructs used by the statement that finds the last column with data in the worksheet are the Worksheet.Cells property, the Range.Find method, and the Range.Column property.
Sub deleteRowBasedOnString() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-delete-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long Dim myCriteriaField As Long Dim myString As String Dim myWorksheet As Worksheet myFirstRow = 5 myFirstColumn = 2 myCriteriaField = 1 myString = "*to delete*" Set myWorksheet = Worksheets("Delete row based on string") With myWorksheet With .Cells myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End With With .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) .AutoFilter Field:=myCriteriaField, Criteria1:=myString On Error Resume Next .Offset(RowOffset:=1).Resize(RowSize:=(.Rows.Count - 1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA deletes the rows containing myString (“*to delete*”) in myCriteriaField (1).
References to VBA Constructs Used in this VBA Tutorial
Use the following links to visit the appropriate webpage within the Microsoft Office Dev Center:
- Identify the worksheet you work with:
- Workbook.Worksheets property.
- Find last row and last column with data in a worksheet and count number of rows in a cell range:
- Range.Find method.
- Range.Count property.
- Return Range objects:
- Application.ActiveCell property.
- Worksheet.Cells property.
- Range.Cells property.
- Range.Offset property.
- Range.Resize property.
- Application.Union method.
- Return Range objects representing rows:
- Worksheet.Rows property.
- Range.Rows property.
- Range.EntireRow property.
- Loop through rows:
- For… Next statement.
- Specify criteria for row deletion:
- DateSerial Function.
- DateValue Function.
- Range.Value property.
- Test if (i) rows meet criteria for deletion, or (ii) the macro has found rows or cells meeting the criteria for deletion:
- If… Then… Else statement.
- Range.AutoFilter method.
- Range.SpecialCells method.
- WorksheetFunction.CountA method.
- Not operator.
- Is operator.
- Delete rows.
- Range.Delete method.
- Work with variables:
- Dim statement.
- Set statement.
- Data types:
- Data data type.
- Double data type.
- Long data type.
- Object data type.
- String data type.
- Variant data type.
- Simplify object references:
- With… End With statement.
- Handle errors:
- On Error statement.
- Remove AutoFilter drop-down arrows:
- Worksheet.AutoFilterMode property.
Удаление пустых строк с помощью кода 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 |
Chris Nielsen’s solution is simple and will work well. A slightly shorter option would be…
ws.Rows(Rand).Delete
…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…
ws.Rows(Rand) = ""
…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
- 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: В сегменте кода объявите подфункцию, чтобы начать писать код.
Код:
Sub Sample () End Sub
Шаг 3: Теперь напишите следующий код, чтобы удалить строку.
Код:
Диапазон Sub Sample () ("A1"). CompleteRow.Delete End Sub
Шаг 4: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.
Запустив код, мы увидим, что значения из ячеек A1 и B1 удаляются, поскольку вся первая строка была удалена.
VBA Delete Row — Пример № 2
Ранее в первом примере я удалил только одну строку. Но что делать, если нам нужно удалить несколько строк? Для демонстрации, у меня есть следующие данные, как показано ниже,
Я хочу удалить все первые пять строк. Выполните следующие шаги, чтобы удалить строку в Excel с помощью VBA.
Шаг 1. На вкладке разработчика щелкните Visual Basic, чтобы открыть редактор VBA.
Шаг 2: В коде объявите подфункцию, чтобы начать писать код,
Код:
Sub Sample1 () End Sub
Шаг 3: Напишите следующий код, показанный ниже, чтобы удалить все пять строк.
Код:
Диапазон Sub Sample1 () ("A1: B5"). CompleteRow.Delete End Sub
Шаг 4: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.
Как только мы запустим код, мы увидим следующий результат: все данные были удалены, что означает, что первые пять строк были удалены, поскольку у нас были данные в первых пяти строках.
Примечание: я вставлю данные обратно в образец листа Excel для демонстрации.
VBA Delete Row — Пример № 3
Теперь у нас есть данные о сотрудниках, и их продажи осуществляются за три месяца: январь, февраль и март. Один из сотрудников был в отпуске и не мог заниматься продажей в течение трех месяцев, поэтому камеры для него пусты. Наша цель — найти эту пустую строку и удалить ее из данных.
Посмотрите на данные ниже,
Выполните следующие шаги, чтобы удалить строку в Excel с помощью VBA.
Шаг 1. На вкладке разработчика щелкните Visual Basic, чтобы открыть редактор Visual Basic.
Шаг 2: Объявите подфункцию в окне кода, чтобы начать писать код,
Код:
Sub Sample2 () End Sub
Шаг 3: Напишите следующий код, чтобы удалить строки с пустыми ячейками.
Код:
Диапазон Sub Sample2 () ("A1: D5"). SpecialCells (xlCellTypeBlanks) .EntireRow.Delete End Sub
SpecialCells — это функция в VBA, которая возвращает нам все ячейки, которые соответствуют нашим условиям, и нашим условием были пустые ячейки в этом диапазоне, поэтому мы использовали функцию xlCellTypeBlanks.
Шаг 4: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.
Запустив код, мы увидим, что строка с пустыми ячейками была удалена.
Примечание: я снова вставлю данные в образец листа Excel для демонстрации.
VBA Delete Row — Пример № 4
Существуют и другие подобные методы удаления строк, например, использование строк и функция удаления. Например, у нас есть данные в строке 4, и я хочу удалить строку 4. Мы можем дать команду Excel для удаления 4- й строки в данных. Посмотрите на скриншот ниже. У меня есть случайные данные в строке 4 в первой ячейке.
Выполните следующие шаги, чтобы удалить строку в Excel с помощью VBA.
Шаг 1. Откройте редактор VBA, щелкнув Visual Basic на вкладке разработчика.
Шаг 2: Объявите подфункцию, чтобы начать писать код.
Код:
Sub Sample3 () End Sub
Шаг 3: Напишите следующий код для удаления 4-й строки.
Код:
Sub Sample3 () Строки (4). Удалить End Sub
Шаг 4: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.
Данные были удалены, так как 4- я строка была удалена сама.
VBA Delete Row — Пример № 5
В приведенном выше коде мы дали диапазон или строку для удаления в самом коде. Теперь давайте примем ввод от пользователя, и он может удалить строку из заданных данных. Например, у меня есть данные о сотрудниках и продажах, как показано ниже, и я хочу, чтобы пользователь выбрал диапазон, из которого пользователь хочет удалить строки с пустыми ячейками. Посмотрите на данные ниже,
Выполните следующие шаги, чтобы удалить строку в Excel с помощью VBA.
Шаг 1: Откройте VB Editor, нажав Visual Basic на вкладке разработчика,
Шаг 2: Объявите подфункцию, чтобы начать писать код.
Код:
Sub Sample4 () End Sub
Шаг 2: Объявите две переменные как диапазон, A и B.
Код:
Sub Sample4 () Dim A как диапазон Dim B как конец диапазона Sub
Шаг 3: Чтобы принять ввод от пользователя для выбора диапазона, который нужно удалить, мы будем использовать функцию поля ввода и сохраним этот ввод в переменной, определенной выше.
Код:
Sub Sample4 () Dim A в качестве диапазона Dim B в качестве набора диапазонов A = Application.InputBox («Выбрать данные», «Образец макроса», Тип: = 8) End Sub
Шаг 4: Установите B = A, чтобы ввод от пользователя можно было сохранить в диапазоне B.
Код:
Sub Sample4 () Dim A в качестве диапазона Dim B в качестве диапазона Set A = Application.InputBox («Выбор данных», «Sample Macro», Тип: = 8) Set B = A End Sub
Шаг 5: Теперь мы удалим данные с пустыми ячейками из диапазона, выбранного пользователем.
Код:
Sub Sample4 () Dim A в качестве диапазона Dim B в качестве диапазона Set A = Application.InputBox («Выбрать данные», «Sample Macro», Type: = 8) Set B = A A.SpecialCells (xlCellTypeBlanks) .EntireRow.Delete End Sub
Шаг 6: Теперь запустите код с помощью кнопки запуска.
Шаг 6: Появляется поле ввода.
Шаг 7: Выберите диапазон от A1: D8 в этом примере. Нажмите OK, чтобы увидеть результат.
Данные с пустыми ячейками были удалены.
То, что нужно запомнить
Есть несколько вещей, которые мы должны помнить об удалении строки в Excel VBA:
- Мы можем удалить строку на основе одной ячейки.
- Мы можем удалить несколько строк, задав диапазон ячеек.
- Мы также можем удалять строки, принимая данные от пользователя.
Рекомендуемые статьи
Это был путеводитель по VBA Delete Row. Здесь мы обсудили, как удалить строку в Excel VBA вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —
- Как использовать функцию замены в VBA?
- Excel Удалить строку ярлык
- VBA Case | Excel Tricks
- Ярлык строки вставки Excel
- Как суммировать несколько строк в Excel?
Содержание
- VBA Delete Entire Row or Column
- 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
- VBA Coding Made Easy
- Delete Duplicate Rows
- Delete Table Rows
- Delete Filtered Rows
- Delete Rows in Range
- Delete Selected Rows
- Delete Last Row
- Delete Columns by Number
- VBA Code Examples Add-in
- Пример макроса для вставки и удаления строк или столбцов на нескольких листах в Excel
- Аннотация
- Дополнительная информация
- Пример макроса с использованием цикла для вставки строк на несколько листов
- Пример макроса для выбора столбца и вставки нового столбца
- Как в excel удалить нужную строку через VBA
- 7 ответов
- Delete a row in Excel VBA
- 4 Answers 4
- Excel vba удалить строку
- удалить строку целиком (VBA)
- Удаление строк VBA
- Как на VBA отловить удаление строки Excel?
- Удаление строки с определенным порядковым номером по всей книге excel
- Удаление определенных строк в Excel
- VBA удаление перекрывающихся строк (Макросы/Sub)
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.
Источник
Пример макроса для вставки и удаления строк или столбцов на нескольких листах в Excel
Аннотация
Эта статья содержит пример макроса Microsoft Visual Basic для приложений (вспомогательная процедура), который можно использовать для вставки или удаления строк или столбцов на нескольких листах в Microsoft Excel.
Дополнительная информация
Корпорация Майкрософт предоставляет примеры программирования только в целях демонстрации без явной или подразумеваемой гарантии. Данное положение включает, но не ограничивается этим, подразумеваемые гарантии товарной пригодности или соответствия отдельной задаче. Эта статья предполагает, что пользователь знаком с представленным языком программирования и средствами, используемыми для создания и отладки процедур. Инженеры службы поддержки Майкрософт могут объяснить функциональность отдельной процедуры. обязаны изменять примеры для реализации дополнительных возможностей или удовлетворения требований конкретных пользователей. Чтобы вставить или удалить строки или столбцы на нескольких листах, используйте команду For Each. Next statement для циклического прохода по всем необходимым листам или выберете строки или столбцы перед выполнением вставки или удаления.
Приведенные ниже примеры макросов работают только с непрерывным диапазоном столбцов или строк.
Пример макроса с использованием цикла для вставки строк на несколько листов
Пример макроса для выбора столбца и вставки нового столбца
Следующий пример макроса выбирает весь столбец перед вставкой новых столбцов:
Источник
Как в excel удалить нужную строку через VBA
7 ответов
Конечно можно. Ставишь на запись макрос, выполняешь какие нужно действия(удаление строки), останавливаешь запись. Открываешь Макросы->Изменить и смотришь какой код получился.
Будет примерно так:
Вообще-то, при удалении строки необходимо уменьшать счётчик, ибо в противном случае могут остаться строки, содержащие «-» (разумеется, если «-» содержатся в смежных ячейках) или начать удаление снизу вверх, т.е.
Private Sub Test()
Application.ScreenUpdating = False
Dim rw&
For rw = 100 To 1 Step -1
If Cells(rw, 1) = «-» And Cells(rw, 2) = «-» Then Rows(rw).Delete
Next
Application.ScreenUpdating = True
Чуть не забыл 🙂 если в дальнейшем потребуется проверять наличие «-» в большем количестве столбцов, чем сейчас, то вместо увеличения And или дополнительного цикла по столбцам, можно программно воспользоваться стандартной функцией рабочего листа =СЧЁТЕСЛИ() (см. листинг)
Private Sub Test2()
Dim rw&, ws As Worksheet
Set ws = ActiveSheet
Источник
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
Источник
Excel vba удалить строку
удалить строку целиком (VBA)
Смотрите также -5 -7 Is Nothing Rows(Columns(1).Find(«*итого*»).Row).Delete
«Итого по корреспондирующемуА каким макросом
нравится, в модуле отследить удаление строки
(имея в виду это обсуждалось (в проверю все ячейки
Dim iColumns AsDim j As
«» Then: при удалении строки Rows(rw).Delete с группой. т.ч. и у строки на empty. Integer Longi = i + 1 сдвигаются, поэтому циклС массивами чуть5. Как я Rows(rw).Delete ‘номер 9
: всем доброго времени: Макрос удаляет вbobosafedОчень надо! данного макроса? кнопку (Лист или
Как повеситься на Лист), и запустил буржуев). Ни в А вот какWith Sheets(«Недостача»).Range(«A2»).CurrentRegionDim i Asarr(i, 1) = лучше писать так:
сложнее в понимании, уже сказал - — 9-й столбец
суток том числе и: Огромное преогромное спасибо,Helen_fireИ еще. Как UserForm) этот код: событие удаления строки на главное окно
одном из топиков с удалением выкручиваться?
iColumns = .Columns.Count Long elemFor .Cells(Rows.Count, 1).End(xlUp).Row
но на Вашем использовать переменную, аHugoизвините, что вас строки, у которых все получилось. : Все очень просто. сделать чтобы перед
Private Sub CommandButton1_Click() я не нашел Книги. Добавил строчку.
решения не найдено. Есть идеи гарантированно
ReDim arr2(1 To
Dim ii AsEnd If To 2 Step примере было бы не 100000 раз: То что там беспокоил в столбце «A»bobosafed Можно взять для, выполнением 1-го макроса
Dim wsh as нигде.Если сможете найти Сходил в Журнал, Мне лично эта
установить факт события? .Rows.Count, 1 To LongNext
-1 так: делать CDate(«20.11.2013″ дата — это
у меня такая пустые ячейки.
: Немного недоглядел - в принципе «итого». (на удаление строки) Worksheet For Each
буду благодарен за откинул строки, связанные
задача, в общем-то,Serg61 iColumns)Dim iColumns As.ClearContents
.
Private Sub Test(). ещё не факт. проблема200?’200px’:»+(this.scrollHeight+5)+’px’);»>Sub Макрос1()У меня из Это будет выглядеть выскакивало окно предупреждения wsh In Thisworkbook.Worksheets
информацию!По мотивам приведённой с активацией меню, не нужна, но: А почему неarr1 = .Value Integer
.Parent.Range(«C1»).Resize(i) = arr()Next Application.ScreenUpdating = False6. Зачем непременно
Видали мы всякихесть таблица иDim arr(), lr
строки удаляется слово так: с определенным текстом wsh.Rows(13).Delete Next End Comanche ссылки http://www.experts-exchange.com/Appl. _20783307.html
тултипов под кнопками я уже ‘завёлся’. защита листа?For j =
With Sheets(1).Range(«A2»).CurrentRegionEnd WithLightZ Dim rw As удалять строки? Может дат. Пока не в 9-й колонке As Long, i «итоги», а мнеRows(Columns(1).find(«*итого*»).row).Delete Shift:=xlUpИли прописатьКазанский Sub вижу наиболее пока инструментальной панели и Очень интересно былоПара кнопок на 2 To .Rows.CountiColumns = .Columns.Countikki
: удалять строки нужно
Long, dDt As
просто переложить данные, докажете — не сущест. даты
As Long, j надо чтоб удалена
удаление каждого по: Нужно запоминать содержимоеКазанский приемлемое решение:
прочую ерунду. И бы ‘родить’ решение.
понели (своей) добавить
If arr1(j, 3)ReDim arr2(1 To: разные способы - снизу вверх
Date, avItems, lLastR затереть ненужное? поверю
больше 100 тыс. As Long была вся строка, отдельности: удаляемых строк. Можно
: Кнопку где? НаDim ExcelSize as что же осталось? Но пока у строку и удалить = «» Then .Rows.Count, 1 To для разных целей.
Daulet As Long lLastRP.S.Упустил — Dimhk1209 строк
Application.ScreenUpdating = False у которойDim mas dim на отдельном скрытом
листе, на форме, Integer ‘ count
— управление скроллом меня ничего красивого строку.i = i + 1
iColumns)использование Delete медленно: ikki, LightZ Спасибо! = Cells(Rows.Count, 9).End(xlUp).Row rw As Date
: Sanja спасибо запроблема такая: надо
lr = Columns(«A:B»).Find(What:=»*»,
в колонке А ind mas=array(«итого по листе, тогда получится на тулбаре, на
Удаление строк VBA
of real rows да repaint-ы. Есть
не выходит. МанипуляцииПричем в этомFor ii =arr1 = .Value в т.ч. потому,
AKSENOV 048
If lLastR
— это ошибка!
подсказку удалить строку целиком, LookIn:=xlFormulas, LookAt:= _
написано «Итоги» ? счету*»,»итого по отделу*»,
сохранить формулы и
рабочем столе, на
Dim SomeArray as
ещё postmessage-строки, но
с Spy++ ничего
случаее не надо 1 To iColumnsFor j = что Ex корректирует
: вот такой вариантP.S. И оформляйтеhk1209
в таблице примерно
если дата меньше
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious,Helen_fire и т.д.) for
форматы. заборе вашей дачи?
Variant ‘ for они повторяются многократно,
пока не дали.
ломать голову какую
arr2(i, ii) =
1 To .Rows.Count все формулы, форматыSub io() коды тегами. Значок: Sanja & Hugo
100 тыс строк 20.11.2013 г. и MatchCase:=False _
: вообще-то этим кодом ind =1 toIf MsgBox(«Строка «В любом случае storeing last user
так что это
Перерыл весь Инет строку пользователь добавляет. arr1(j, ii)If arr1(j, 3) и прочие свойстваSheets(«Недостача»).UsedRange.Offset(1).Columns(«C»).SpecialCells(xlBlanks).Rows.Delete «» среди кнопок
спасибо за подсказкуиспользую следующий код: поднимать на вверх, SearchFormat:=False).Row удаляется строка целиком. кол-во пунктов удаления & n &
кнопке надо будет Selection Private Sub не то, что — тоже без
daniel default
Next
<> «» Then ячеек — примечания,
End Sub вверху при создании
и потраченное драгоценноеPrivate Sub Test()написал следующий код,
arr() = Range(«A1:A»Gopronotmore
Rows(Columns(1).find(mas(ind-1)).row).Delete Shift:=xlUp Next » будет УДАЛЕНА
назначить этот код.
Worksheet_Change(ByVal Target As ищем.
толку.
: В этом случае
End If
i = i + 1
УФ, .
правде если пустых сообщения. время
Application.ScreenUpdating = False но неработает, прошу & lr).Value: Добрый день формучане!bobosafed во всех листах.»nivybuct
Range) ‘for additionsПолучается, что выбор2SlavaRus: вы пишите: придётся контролировать действияNextFor ii =вариант с массивом ячеек не будет,HugoHugo переписал код Dim rw As
вашей подсказкиFor i = Вопрос вот мучаюсь
: По первой формуле & vbLf &
: Но удаляется только If UsedRange.Rows.Count >
пункта меню отловить ‘Если да, то юзера и вSheets(«Недостача»).Range(«A2:C» & Cells(Rows.Count, 1 To iColumns
действительно много быстрее,
появиться ошибка. тогда: Супербыстрое удаление строк по вашим замечаниям, Date For rwPrivate Sub Test() 1 To UBound(arr,
с таблицей в получается, но строчки _ «Продолжить?», vbExclamation строка №13? ExcelSize Then DoSomethingInAddCase(UsedRange.Rows.Count можно, но его
проблему можно решить!’. других, не интересующих 1).End(xlUp).Row).ClearContentsarr2(i, ii) = но с формулами
можно добавить обработчик
от ZVI есть
к сожалению не = 100000 To
Application.ScreenUpdating = False 1)
которой много значений. с разными текстами
+ vbDefaultButton2 +mc-black
— ExcelSize) ExcelSize
нажатие никаких мессаджей
КАК? Поделитесь. меня зонах, аSheets(«Недостача»).Range(«A2»).Resize(i, iColumns).Value =
arr1(j, ii)
и форматами придется ошибок.
тут: работает
1 Step -1
Dim rw AsIf (IsNumeric(arr(i, 1))
Задача вот в за один клик
vbYesNo) = vbNo
: Private Sub CommandButton1_Click()
= UsedRange.Rows.Count ‘for
не посылает. НичегоИтак, что имеем:
это ненужный код, arr2
Next
распрощаться. а ужDauletМожно использовать иPrivate Sub Test() If Cells(rw, 9) Date For rw = False) Or чем. Есть список не удаляются. Например, Then Exit Sub Dim wsh As deletions ElseIf UsedRange.Rows.Count
удивительного — просто1. Удалить из время. Или яEnd WithEnd If если на этот: AKSENOV 048 Спасибо
в этой задаче. Dim rw As
Как на VBA отловить удаление строки Excel?
субсчету» надо запускать ситуация: на листе2 строки», «Ввести число», End If End можем отлавливать (а на ‘свои’. если юэаем Excel
тогда удаляет иSheets(1).Range(«A2»).Resize(i, iColumns).Value = результат может быть что надо НЕ даты
xlCalculationManual Application.ScreenUpdating =есть ли у Rows(rw).Delete ‘номер 9For j = со знаком - макрос два раза, таблица связана с 13) For Each Sub Private Sub по-другому и никак),3. Через BeforeRightClick
XP, то можно ругается на строку arr2
катастрофическим :) пустые ячейки удалять)hk1209 False For rw
вас какие-то идеи — 9-й столбец i + 1Как написать скрипт
чтобы удалить эти таблицей листа1. На wsh In ThisWorkbook.Worksheets Worksheet_SelectionChange(ByVal Target As то получится, что запретить popup-меню на защитить листь от (Ошибка 1004)End With
KuklP простите.: The_Prist спасибо за = ActiveSheet.UsedRange.Row + для оптимизации данного Next Application.ScreenUpdating = To UBound(arr, 1) который при просмотре
строки листе3 — не wsh.Rows(n).Delete Next End Range) StoreTargetInSomeArray(Target) ‘ будем запрещать нажатие листе.
вставки строк, а->Sheets(«Недостача»).Range(«A2»).Resize(i, iColumns).Value =KuklP: Богдан, это с
SpecialCells(xlConstants, 1) потраченное драгоценное время
ActiveSheet.UsedRange.Rows.Count — 1 кода? True End SubспасибоIf (IsNumeric(arr(j, 1)) диапазона удалял строкиВо второй формуле
связанная с другими Sub
I don’t now
пункта меню. А
4. Манипуляции с
остальное как бы
arr2: Да хоть Do одним массивом:-)LightZ и советы (включая To FirstRow Stepкаждый раз кол-во за потраченное драгоценное = True) And которые в сумме — макрос ругается листами информация.nivybuct how to realize тогда возникает резонный защитой листа. не защищать. спасибо Вам ну loop. Там вLightZ: ABC, если Вы код) -1 If Cells(Rows.Count, строк разные бывает
время (IsEmpty(arr(j, 1)) = дают 0 . на строку
Нужны два макроса:
: Я плохо сформулировал correctly analog of вопрос: на фига
5. Манипуляции сdaniel default
туда добавлю Error любом случае один: KukLP
будете удалять строкиHugo — спасибо
9).End(xlUp).Row
Удаление строки с определенным порядковым номером по всей книге excel
Daulet быстрей), тогда да.ikki скорость 00:00 сек,: Здравствуйте!прошу вашей помощиSanja
в данном случаеExit For квитовать одну строку меня такая строка с сохранением целостности строку.
порядковым номером ещё ссылка, где мой взгляд, тут или удаления строки?: LightZ охо прекрасноKuklPИсходил из скорости
а выполнение вышеуказанныхХочу удалить строкспасибо за понимание
: Для ускорения выполнения к дате, аEnd If +10 с тремя работает.из индекса вычитается
таблиц (форматирование, пересчетВыделяю еепо всей книге мне на этот нет. Красивым былоЕсли да, то
спасибо Вам!: Теперь, да. Только выполнения макроса, т.к. кодов так и не пустых ячеекThe_Prist
кода отключите автоматический вернее справа можетEnd If
строками -3, -6, 1, поскольку нумерация формул), но только
, запускаю нужный макрос.excel? же вопрос отвечала бы решение с проблему можно решить!daniel default и для этого примера нет и не дождался :( столбце C, или: Cells(Rows.Count, 9).End(xlUp).Row
Удаление определенных строк в Excel
With Sheets(«Недостача») 0. Как минимум номер последней строки
датаOn Error Resume дают одно значение, этот момент надоэта музыка будет вечной?
mc-black Next End Sub: Да, весьма толково — непонятно. Как
решение красивее?
листа не годится): LightZ Ваш последний но скорее всегоDim arr()For d = под конец ошибку
с данными вwowick Next
просто нужно затереть учитывать.скиньте скрин ошибки. :D: Private Sub CommandButton1_Click()nivybuct ответила, ничего не уже говорил, Spy++
daniel defaultIgorTr код массивный замечателен, не оригинал, дляDim i As 2 To .Cells(Rows.Count,
получите. 9-м столбце:: А сравниваете выRange(«A1»).Resize(UBound(arr, 1), 1).SpecialCells(xlCellTypeBlanks).EntireRow.Delete повторы грубо говоряА насчет первогоbobosafed
Dim wsh As: Большое спасибо за скажешь.
мне не помог.
: http://www.relib.com/forums/topic.asp?id=742255: ИМХО больной вопрос.
но чуть исправил которого делается макрос Long 1).End(xlUp).RowHugo совсем иноеCells(Rows.Count, 9).End(xlUp).Row ее с ТЕКСТОМOn Error GoTo есть 3 числа варианта:я просто скидывала: Помогите чайнику! Я Worksheet, n As быстрый ответ! НоСклоняюсь я к Я отрубил в
http://www.relib.com/forums/topic.asp?id=798944 Красиво сделать ЭТОDim arr1() :)With Sheets(1).Range(«C1:C» &If .Cells(d, 3).Value советовал..
Hugo «20.11.2013». В экселе,
0 3 5 7 вариант строки, а
только учусь Long n = мне нужно создать
тому, что это, нём фиксацию сообщений
http://www.relib.com/forums/topic.asp?id=747125 мне пока неDim arr2()LightZ Cells(Rows.Count, 3).End(xlUp).Row) <> «» Then
До начала цикла:: 4. Обрабатывать массивы,
как и во-многихApplication.ScreenUpdating = True и есть 3
VBA удаление перекрывающихся строк (Макросы/Sub)
так его тожеНадо в таблице Selection.Row For Each кнопку, которая бы наверное, наилучший вариант
типа ‘Mouse’ иhttp://www.experts-exchange.com/Applications/MS_Office/Excel/Q_20783307.html удалось :-(Dim j As: вот так будетReDim arr(1 To.Rows(d).EntireRow.Delete
dim dDt as а не ячейки других средах программированияMsgBox «Готово!», vbInformation числа -3 -5
надо было ставить
Excel удалить строки wsh In ThisWorkbook.Worksheets удаляла выделенную строку решения задачи. ‘Keyboard’ (чтоб неhttp://www.excel-center.com/mailing/137701h.htmdaniel default Long лучше, учитывая все .Cells.Count, 1 ToEnd If
Date dDt = — на листе в кавычках подразумеваетEnd Sub -7 если есть в цикл, и в графе А wsh.Rows(n).Delete Next End по всей книге.Там осталось несколько таким здоровым былdaniel default: Ну хорошо, пустьDim i As данные, с двумя 1)Next
CDate(«20.11.2013»)И уже в только удалять строки, текстовый формат.Gopronotmore совпадение, то удалить потом использовать FindNext.
в которых указаны
Submc-black неясностей. Если решишь журнал), затем настроил
: 2IgorT: да уж,
не слишком красиво. Long
массивами:For Each elem
End With
цикле: да и тут
Sanja: Да вы просто строки где есть
А лучше сделайте тексты :nivybuct: Дежурный экстрасенс вышел
(или уже знаешь
на фиксацию сообщений
‘больной вопрос’. Я С вставкой ещёDim ii As
Dim arr1() In .ValueEnd SubIf Cells(rw, 9)
можно это делать: Попробуйте так бог! Спасибо огромное
числа 3 5 цикл еще короче
»Итого по счету»,: Спасибо! То что
покурить.
как), напиши, пожалуйста,
как окна, так
предыдущим сообщением перечислил
куда ни шло:
Long
Dim arr2()If elem <>
ikki
нужно.Кнопку поместить где сюда.По событию CHANGE и его ‘детей’
Источник
Добрый день.
Подскажите пожалуйста, задача следующая:
Необходимо пройтись по всем рядам таблицы.
Если в колонке А стоит «-» и в колонке В стоит «-«, то данную строку необходимо удалить.
Можно ли реализовать данную задачу через макросы?
Спасибо.
7 ответов
37K
06 марта 2013 года
freets
97 / / 15.10.2010
Конечно можно. Ставишь на запись макрос, выполняешь какие нужно действия(удаление строки), останавливаешь запись. Открываешь Макросы->Изменить и смотришь какой код получился.
Будет примерно так:
Код:
Rows(«1:1»).Select //выделяем первую строку
Selection.Delete Shift:=xlUp //удаляем со сдвигом вверх
только добавь нужное условие и всё.
88K
06 марта 2013 года
Vanderlog
4 / / 06.03.2013
А как правильно организовать перебор всех элементов, и, собственно, если не трудно то условие скажите как задать?
37K
06 марта 2013 года
freets
97 / / 15.10.2010
Код:
Sub Macros()
Dim rw As Long
For rw = 1 To 100
If Cells(rw, «A»).Value = «-« And Cells(rw, «B»).Value = «-« Then
Rows(rw & «:» & rw).Delete Shift:=xlUp
End If
Next rw
End Sub
88K
06 марта 2013 года
Vanderlog
4 / / 06.03.2013
Работает, но почему-то за один проход не справляется. Причем строк меньше 100. 10 строк удаляет за 4 прохода. Что может останавливать скрипт?
275
06 марта 2013 года
pashulka
985 / / 19.09.2004
Вообще-то, при удалении строки необходимо уменьшать счётчик, ибо в противном случае могут остаться строки, содержащие «-» (разумеется, если «-» содержатся в смежных ячейках) или начать удаление снизу вверх, т.е.
Код:
Private Sub Test()
Application.ScreenUpdating = False
Dim rw&
For rw = 100 To 1 Step -1
If Cells(rw, 1) = «-» And Cells(rw, 2) = «-» Then Rows(rw).Delete
Next
Application.ScreenUpdating = True
End Sub
88K
06 марта 2013 года
Vanderlog
4 / / 06.03.2013
Все верно, при переборе снизу вверх работает корректно. Спасибо всем!
275
22 марта 2013 года
pashulka
985 / / 19.09.2004
Чуть не забыл если в дальнейшем потребуется проверять наличие «-» в большем количестве столбцов, чем сейчас, то вместо увеличения And или дополнительного цикла по столбцам, можно программно воспользоваться стандартной функцией рабочего листа =СЧЁТЕСЛИ() (см. листинг)
Код:
Private Sub Test2()
Dim rw&, ws As Worksheet
Set ws = ActiveSheet
With Application
.ScreenUpdating = False
For rw = 100 To 1 Step -1
If .CountIf(ws.Cells(rw, «A»).Resize(, 2), «-«) = 2 Then ws.Rows(rw).Delete
Next
.ScreenUpdating = True
End With
End Sub
P.S. Разумеется номер последней заполненной строки мы можем определять программно.