Как удалить диапазон ячеек в excel vba

Программное удаление ячеек в VBA Excel со сдвигом влево или со сдвигом вверх методом Delete объекта Range. Константы XlDeleteShiftDirection.

Range.Delete – это метод, удаляющий объект Range (диапазон ячеек, одну ячейку) со сдвигом замещающих ячеек справа-налево или снизу-вверх для замены удаленных ячеек.

Синтаксис

Expression.Delete (Shift)

Expression – выражение (переменная), возвращающее объект Range.

Параметры

Параметр Описание
Shift Константа из коллекции XlDeleteShiftDirection, определяющая способ сдвига замещающих ячеек для замены удаленных ячеек.

Если параметр Shift опущен, Microsoft Excel самостоятельно выберет способ сдвига замещающих ячеек в зависимости от формы диапазона.

Константы XlDeleteShiftDirection:

Константа Значение Описание
xlShiftToLeft -4159 Замещающие ячейки сдвигаются справа-налево.
xlShiftUp -4162 Замещающие ячейки сдвигаются снизу-вверх.

Примеры

Удаление ячейки со сдвигом влево:

ActiveCell.Delete xlShiftToLeft

Range(«D4»).Delete xlShiftToLeft

Cells(6, 8).Delete xlShiftToLeft

Удаление диапазона со сдвигом вверх:

Selection.Delete xlShiftUp

Range(«E3:H9»).Delete xlShiftUp


Skip to content

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates
  • VBA to Delete Range in Excel – Syntax
  • VBA to Delete Range in Excel – Example:Shift:=xlToLeft
  • VBA to Delete Range in Excel – Example:Shift:=xlToUp
  • VBA to Delete Range in Excel – Example: EntireRow
  • VBA to Delete Range in Excel – Example: EntireColumn
    • VBA to Delete Range in Excel – Execution Instructions

Page load link

Go to Top

In this Article

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

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

Delete Entire Row or Column

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

Rows(1).Delete

Notice we use the Delete method to delete a row.

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

Range("a1").EntireRow.Delete

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

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

Delete Multiple Rows or Columns

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

Rows("1:3").Delete

or columns:

Columns("A:C").Delete

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

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

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

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

Delete Blank / Empty Rows

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

Sub DeleteRows_EntireRowBlank()

Dim cell As Range

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

End Sub

It makes use of the Excel worksheet function: COUNTA.

Delete Row if Cell is Blank

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

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

Delete Row Based on Cell Value

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

Sub DeleteRowswithSpecificValue()

Dim cell As Range

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

End Sub

More Delete Row and Column Examples

VBA Coding Made Easy

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

automacro

Learn More

Delete Duplicate Rows

This code will delete all duplicate rows in a range:

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

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

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

Delete Table Rows

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

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

Delete Filtered Rows

To delete only rows that are visible after filtering:

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

VBA Programming | Code Generator does work for you!

Delete Rows in Range

This code will delete all rows in range:

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

Delete Selected Rows

This code will delete all selected rows:

Selection.EntireRow.Delete

Delete Last Row

This will delete the last used row in column B:

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

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

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

Delete Columns by Number

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

Columns (2).Delete
 

требуется очистить ячейки, нашел только макрос «удалить»  

  rivate Sub CommandButton2_Click()  
Range(«B17:K500»).Delete  
End Sub  

    замена Delete -> Clean  не сработала :)))

 

KuklP

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

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

E-mail и реквизиты в профиле.

Попробуйте clear. Или clearcontents.

Я сам — дурнее всякого примера! …

 

Range(«B17:K500»).Select  
   Selection.ClearContents

 

vikttur

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

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

Clear  
ClearContents  

  Чаще справку читайте.

 

Hugo

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

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

Зачем искать?  
Для этого есть макрорекордер — включаем, стираем (через Delete), выключаем, смотрим:  

     Range(«A1:A6»).Select  
   Selection.ClearContents  

      выкидываем ненужное:    
       Range(«A1:A6»).ClearContents  

  Если аналогично сделать через меню «очистить всё», то получим  
       Range(«A1:A6»).Clear

 

Формат не удаляет:  
Range(«B17:K500»).ClearContents  

  Формат удаляет:  
Range(«B17:K500»).Clear

 

формат должен оставаться.  

  всем пасибо!  

    тема клозет

 

vikttur

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

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

Говорил же автору — больше нужно читать :)  

  closet — каморка  
клозет — устар. помещение для отправления естественных надобностей

 

Юрий М

Модератор

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

Контакты см. в профиле

#9

09.07.2012 09:52:32

{quote}{login=d-konstruktor}{date=09.07.2012 09:45}{thema=}{post}тема клозет{/post}{/quote}Клозет — помещение для отправления естественных надобностей.  
Вы хотите открыть новую тему? :-)

Managing and removing named ranges in Excel can be a challenging task as you would have to do this one by one for each field. We’re going to show you how to delete named range Excel using VBA with one click.

How to delete named range Excel

Each named range is an object in the Names collection of a workbook. We can access these names using a For Each…Next loop and checking their references with the RefersToRange method. The RefersToRange method returns the reference as a Range object that we can use to find its parent worksheet.

The worksheet name a named range belongs to can be found with Name property under the Parent method. Then, using an If statement you can find the parent worksheet name.

    For Each nm In ActiveWorkbook.Names

        If nm.RefersToRange.Parent.Name = «Sheet1» Then nm.Delete

    Next nm

 

You can use codes in two ways:

  • Module
  • Immediate Window

In the Module method, you need to add the module into the workbook or the add-in file. Copy and paste the code into the module to run it. The main advantage of the module method is that it allows saving the code in the file, so that it can be used again later. Furthermore, the subroutines in modules can be used by icons in the menu ribbons or keyboard shortcuts. Remember to save your file in either XLSM or XLAM format to save your VBA code.

The Immediate Window method, on the other hand, is essentially a quick and dirty method where you can simply copy and paste the code into the Immediate Window and press the Enter key to run it. Unfortunately, any code you use in the Immediate Window will not be saved. Also note that icons and keyboard shortcuts will not be available.

Delete named ranges in a worksheet

Module method:

Sub DeleteNamedRangesInWorksheet()

    Dim nm As Name

    For Each nm In ActiveWorkbook.Names

        If nm.RefersToRange.Parent.Name = «Sheet1» Then nm.Delete

    Next nm

End Sub

 

Immediate Window method:

For Each nm In ActiveWorkbook.Names: If nm.RefersToRange.Parent.Name = "Sheet1" Then nm.Delete: Next nm

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Как удалить дублирование в excel
  • Как удалить все ячейки с определенным значением в excel
  • Как удалить границы ячейки в excel
  • Как удалить выбросы excel
  • Как удалить действие в excel

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии