Vba excel очистить колонку

Метод Range.Clear для полной очистки диапазона ячеек из кода VBA Excel. Методы очистки отдельных свойств и их групп в ячейках. Примеры использования.

Методы очистки ячеек

Метод Очищаемые свойства Примечание
Range.Clear Почти все свойства Ширина и высота ячеек не изменяются
Range.ClearComments Комментарии Для Excel в составе Office 365
Range.ClearContents Формулы и значения Исходное форматирование сохраняется
Range.ClearFormats Свойства, задающие форматы В том числе отмена объединения ячеек
Range.ClearHyperlinks Гиперссылки Текст и форматирование сохраняются
Range.ClearNotes Примечания и заметки Примечания – для локальных программ Excel, заметки – для Excel в составе Office 365
Range.ClearOutline Структура данных Смотрите, что такое структурирование данных

Range – выражение, возвращающее диапазон ячеек.

Примеры использования

1. Удаление гиперссылки из ячейки A1
Cells(1, 1).ClearHyperlinks

2. Очистка диапазона A1:L50 от формул и значений
Range("A1:L50").ClearContents

3. Очистка всех свойств ячеек в столбцах A:K
Columns("A:K").Clear

4. Очистка форматирования ячеек в строках 1:20
Rows("1:20").ClearFormats

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


Фразы для контекстного поиска: очистка ячеек, очистка ячейки, очистка формул, очистка от формул, удаление формул, очистка значений, удаление значений, очистка форматов, удаление форматирования, удаление форматов.


In this Article

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

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

Delete Entire Row or Column

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

Rows(1).Delete

Notice we use the Delete method to delete a row.

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

Range("a1").EntireRow.Delete

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

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

Delete Multiple Rows or Columns

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

Rows("1:3").Delete

or columns:

Columns("A:C").Delete

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

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

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

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

Delete Blank / Empty Rows

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

Sub DeleteRows_EntireRowBlank()

Dim cell As Range

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

End Sub

It makes use of the Excel worksheet function: COUNTA.

Delete Row if Cell is Blank

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

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

Delete Row Based on Cell Value

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

Sub DeleteRowswithSpecificValue()

Dim cell As Range

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

End Sub

More Delete Row and Column Examples

VBA Coding Made Easy

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

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

Содержание

  1. VBA Delete Entire Row or Column
  2. Delete Entire Row or Column
  3. Delete Multiple Rows or Columns
  4. Delete Blank / Empty Rows
  5. Delete Row if Cell is Blank
  6. Delete Row Based on Cell Value
  7. More Delete Row and Column Examples
  8. VBA Coding Made Easy
  9. Delete Duplicate Rows
  10. Delete Table Rows
  11. Delete Filtered Rows
  12. Delete Rows in Range
  13. Delete Selected Rows
  14. Delete Last Row
  15. Delete Columns by Number
  16. VBA Code Examples Add-in
  17. VBA Excel. Range.Clear и другие методы очистки ячеек
  18. Методы очистки ячеек
  19. Примеры использования
  20. 6 комментариев для “VBA Excel. Range.Clear и другие методы очистки ячеек”
  21. VBA Delete Column
  22. Excel VBA Delete Column
  23. What Does Delete Column Do in Excel VBA?
  24. Examples of Excel VBA Delete Column Method
  25. Example #1 – Using Delete Method
  26. Example #2 – Delete Columns with Worksheet Name
  27. Example #3 – Delete Blank Columns
  28. Example #4 – Delete Blank Cells Columns
  29. Recommended Articles
  30. VBA Удалить столбец — Как удалить столбец в Excel, используя код VBA?
  31. VBA Удалить столбец
  32. Синтаксис для удаления столбца в Excel VBA
  33. Как удалить столбец в Excel с помощью VBA?
  34. VBA Удалить столбец — Пример № 1
  35. VBA Удалить столбец — Пример № 2
  36. VBA Удалить столбец — Пример № 3
  37. VBA Удалить столбец — Пример № 4
  38. VBA Удалить столбец — Пример № 5
  39. То, что нужно запомнить
  40. Рекомендуемые статьи

VBA Delete Entire Row or Column

In this Article

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

Delete Entire Row or Column

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

Notice we use the Delete method to delete a row.

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

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

Delete Multiple Rows or Columns

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

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

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

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

Delete Blank / Empty Rows

Delete Row if Cell is Blank

Delete Row Based on Cell Value

More Delete Row and Column Examples

VBA Coding Made Easy

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

Delete Duplicate Rows

This code will delete all duplicate rows in a range:

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

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

Delete Table Rows

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

Delete Filtered Rows

To delete only rows that are visible after filtering:

Delete Rows in Range

This code will delete all rows in range:

Delete Selected Rows

This code will delete all selected rows:

Delete Last Row

This will delete the last used row in column B:

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

Delete Columns by Number

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

VBA Code Examples Add-in

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

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

Источник

VBA Excel. Range.Clear и другие методы очистки ячеек

Метод Range.Clear для полной очистки диапазона ячеек из кода VBA Excel. Методы очистки отдельных свойств и их групп в ячейках. Примеры использования.

Методы очистки ячеек

Метод Очищаемые свойства Примечание
Range.Clear Почти все свойства Ширина и высота ячеек не изменяются
Range.ClearComments Комментарии Для Excel в составе Office 365
Range.ClearContents Формулы и значения Исходное форматирование сохраняется
Range.ClearFormats Свойства, задающие форматы В том числе отмена объединения ячеек
Range.ClearHyperlinks Гиперссылки Текст и форматирование сохраняются
Range.ClearNotes Примечания и заметки Примечания – для локальных программ Excel, заметки – для Excel в составе Office 365
Range.ClearOutline Структура данных Смотрите, что такое структурирование данных

Range – выражение, возвращающее диапазон ячеек.

Примеры использования

1. Удаление гиперссылки из ячейки A1
Cells(1, 1).ClearHyperlinks

2. Очистка диапазона A1:L50 от формул и значений
Range(«A1:L50»).ClearContents

3. Очистка всех свойств ячеек в столбцах A:K
Columns(«A:K»).Clear

4. Очистка форматирования ячеек в строках 1:20
Rows(«1:20»).ClearFormats

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

Фразы для контекстного поиска: очистка ячеек, очистка ячейки, очистка формул, очистка от формул, удаление формул, очистка значений, удаление значений, очистка форматов, удаление форматирования, удаление форматов.

6 комментариев для “VBA Excel. Range.Clear и другие методы очистки ячеек”

Здравствуйте!
Есть такая проблема:
1. В отдельном модуле написана процедура, которая при запуске и вводе в inputbox данных генерирует таблицу с данными. Вот перед каждой генерацией сделал так, чтобы содержимое листа , кроме первой строки (шапки), очищалось: Thisbooks.Worksheets(«Лист3»).Range(«A2»,Cells(lastRow, lastColumn).clear

2. На первом листе у меня как бы меню управления. Там кнопка, к которой привязана эта процедура. При запуске выполнение процедуры доходит до строки с очисткой и уходит в ошибку 1004 run time error: Application-defined or object-defined error.

При этом, если эту же процедуру запускать с кнопки, или через F5, но с открытого Лист3 — все отлично выполняется!

Никак не могу додуматься в чем же проблема. Подскажите пожалуйста!

Источник

VBA Delete Column

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

Excel VBA Delete Column

We perform many actions in Excel like cutting, copying, pasting, adding, deleting, and inserting regularly. We can use all of these actions using VBA coding. However, one of the important concepts we need to learn in VBA is the “deleting column.” This article will show you how to use this “Delete Column” option in VBA.

Table of contents

What Does Delete Column Do in Excel VBA?

As the name says, it will delete the specified column. To perform this task, we must first identify which column to delete. The selection of deleted columns differs from one scenario to another, so that we will cover some of the important and often faced scenarios in this article.

Deleting the columns is easy. First, we need to use the COLUMNS property to select the column, so VBA’s syntax of the “Delete Column” method is below.

Columns (Column Reference).Delete

So, we can construct the code like this:

It will delete column number 2, i.e., column B.

If we want to delete multiple columns, we cannot enter columns. Instead, we need to reference the columns by column headers, i.e., alphabets.

It will delete the column from A to D, i.e., the first 4 columns.

Like this, we can use the “Delete Column” method in VBA to delete particular columns. In the below section, we will see more examples to understand it better. Read on.

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA Delete Column (wallstreetmojo.com)

Examples of Excel VBA Delete Column Method

Below are examples of deleting columns using VBA.

Example #1 – Using Delete Method

Assume you have the datasheet, something like the below.

If we want to delete the month “Mar,” first select the column property.

Code:

Mention the column number or alphabet. In this case, it is either 3 or C.

Code:

Use the Delete method.

Note: You would not get the IntelliSense list to select the Delete method. Just type “Delete.”

Code:

Or you can enter the column address like this.

Code:

Run this code using the F5 key, or you can run it manually and see the result.

Both the codes will do the same job of deleting the mentioned column.

If we want to delete multiple columns, we need to mention them in the alphabet. We cannot use column numbers here.

If we want to delete columns 2 to 4, we can pass the code like the below.

Code:

Run this code manually through the run option or press the F5 key. It will delete the columns “Feb,” “Mar,” and “Apr.”

Example #2 – Delete Columns with Worksheet Name

The above is an overview of how to delete columns using VBA code. However, that is not a good practice to delete columns. Deleting the column without referring to the worksheet name is dangerous.

If you have not mentioned the worksheet name, then whichever sheet is active will delete columns of that sheet.

First, we need to select the worksheet by its name.

Code:

Code:

It will delete columns B to D of the worksheet “Sales Sheet.” For this code, it does not matter which is active. Still, it will delete the mentioned columns of that sheet only.

Code:

It also deletes the columns “B to D” without selecting the worksheet “Sales Sheet.”

Example #3 – Delete Blank Columns

Assume you have data that has alternative blank columns like the below.

So, delete every alternate column. Then, we can use the below code.

Code:

Run this code using the F5 key or manually. Then, it will delete all the alternative blank columns, and our data will look like this.

Note: This works only for alternative blank columns.

Example #4 – Delete Blank Cells Columns

Now, look at this example. In certain situations, we need to delete the entire column if we find any blank cells in the data range. Consider the below data for an example.

All the yellow-colored cells are blank. So here, we require to delete all the blank cell columns. The below code will do that.

Code:

Let me explain this code line by line for you.

Our data is from A1 to F9, so first, we must select that range. The below code will do that.

We need to select the blank cells in this selected range of cells. So, to select a blank cell, we need a special cell property. In that property, we have used cell type as blank.

Next, it will select all the blank cells, and we are deleting the entire selection column in the selection.

So, our result will look like this.

Wherever it has found the blank cell, it has deleted those blank cells entirely.

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

Recommended Articles

This article has been a guide to VBA Delete Column. Here, we learn four methods to delete columns using Excel VBA code, practical examples, and downloadable codes. Below are some useful Excel articles related to VBA: –

Источник

VBA Удалить столбец — Как удалить столбец в Excel, используя код VBA?

VBA Удалить столбец

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

Метод удаления столбцов используется для удаления одного или нескольких столбцов в Excel VBA. Свойство delete для столбцов используется вместе с индексом столбца.

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

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

  • Где ссылка на столбец — это номер столбца, который вы хотите удалить.
  • Столбцы ((RowIndex), ColumnIndex)) здесь диапазон столбцов также принимается.

Как удалить столбец в Excel с помощью VBA?

Мы узнаем, как удалить столбец в VBA, с несколькими примерами в Excel.

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

VBA Удалить столбец — Пример № 1

Из базы данных посещаемости указывается время отъезда в офис для некоторых сотрудников. Это данные, собранные за одну неделю, с понедельника по пятницу.

Мы хотим удалить столбец пятница.

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

Шаг 1: Итак, сначала мы можем создать простую функцию как delete (), поскольку delete — это ключевое слово, которое не является предпочтительным.

Код:

Шаг 2: Теперь давайте использовать свойство columns.

Код:

В столбцах () упоминается «6», поскольку указанный столбец является 6- м столбцом в таблице.

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

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

VBA Удалить столбец — Пример № 2

Другой простой способ выполнить удаление — указать ссылку на столбец в алфавитном порядке.

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

Шаг 1: Поскольку пятница — это столбец F, укажите адрес столбца, как показано ниже в коде.

Код:

При использовании алфавита не забудьте поставить алфавит в двойных кавычках.

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

Это удалит столбец пятница из таблицы.

VBA Удалить столбец — Пример № 3

В той же таблице, если вы хотите удалить более одного столбца, следует указать диапазон столбцов.

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

Шаг 1: Код можно изменить, как показано ниже.

Код:

Диапазон указан как «E: F», и это приведет к удалению столбца от F до G.

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

Последние два столбца удалены.

VBA Удалить столбец — Пример № 4

Посмотрим, что будет, если мы удалим средние столбцы в таблице.

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

Шаг 1: Код можно изменить, как показано ниже.

Код:

Здесь «B: C» относится к колонке понедельник и вторник.

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

После запуска кода, если вы проверите таблицу, вы можете увидеть столбец после смещения «B: C» справа налево.

VBA Удалить столбец — Пример № 5

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

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

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

Шаг 1: лист должен быть выбран с помощью кода.

Код:

Шаг 2: Теперь нужно указать код для удаления столбца.

Код:

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

Будет выбран лист «Jan», а столбцы B, C, т.е. понедельник, вторник, будут удалены из таблицы.

Удаление нескольких столбцов с использованием объекта диапазона в VBA

Объект диапазона также используется для удаления столбца в VBA вместо удаления столбца. Если используется объект диапазона, код будет выглядеть так, как показано ниже.

Диапазон («B: C») представляет собой диапазон столбцов, который необходимо удалить.

Удаление одного столбца с использованием объекта диапазона

Чтобы удалить один столбец с использованием объекта диапазона, необходимо указать диапазон, как показано ниже.

Диапазон («B: B») указывает на один столбец, и он будет удален.

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

  • Столбец может быть указан с помощью номера столбца или соответствующего алфавита при удалении.
  • При удалении нескольких столбцов номера не будут приняты в качестве ссылки на столбец.
  • Вместо свойства столбцов можно использовать объект Range для удаления столбца в VBA.

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

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

  1. Удаление строки с помощью VBA
  2. Excel Переместить столбцы
  3. Транспонировать диапазон в VBA
  4. Excel Удалить строку ярлык

Источник

Excel VBA Tutorial about how to clear cell with macrosIn this VBA Tutorial, you learn how to clear cells (including clearing cells totally, their format but not their contents, their contents but not their format, and other similar combinations) with macros.

This VBA Tutorial is accompanied by Excel workbooks containing the macros I use in the examples below. You can get immediate 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 important VBA constructs here.
    • Learn how to work with the Visual Basic Editor here.
    • Learn how to work with Excel Sub procedures here.
    • Learn about the Excel Object Model, and how to create object references, here.
    • Learn about the Range object, and how to refer to cells, here.
    • Learn how to work with properties here.
    • Learn how to work with methods here.
    • Learn how to declare and work with variables here.
    • Learn about data types here.
    • Learn how to work with loops here.
  • Practical VBA applications and macro examples:
    • Learn how to work with worksheets using VBA here.
    • Learn how to check if a cell is empty here.
    • Learn how to delete rows here.
    • Learn how to delete blank or empty rows here.

You can find additional VBA and Macro Tutorials in the Archives.

VBA Code to Clear Cell

To clear cells using VBA, use a statement with the following structure:

Cells.Clear

Process Followed by VBA to Clear Cell

Identify cells to clear > clear cells entirely

VBA Statement Explanation

  1. Item: Cells.
    • VBA Construct: Range object.
    • Description: Range object representing the cells you want to clear.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset, Range.Resize or Application.ActiveCell properties. If you explicitly declare an object variable to represent Cells, use the Range object data type.

  2. Item: Clear.
    • VBA Construct: Range.Clear method.
    • Description: The Range.Clear method clears the Range object you specify (Cells). Range.Clear clears the entire Range object, including values, formulas and formatting.

Macro Example to Clear Cell

The following macro example clears cells A5 to C9 (myRange) in the worksheet named “Clear Cell” of the workbook containing the macro (ThisWorkbook).

Sub clearCell()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-clear-cell/

    'declare object variable to hold reference to cells to clear
    Dim myRange As Range

    'identify cells to clear
    Set myRange = ThisWorkbook.Worksheets("Clear Cell").Range("A5:C9")

    'clear cells (including formatting)
    myRange.Clear

End Sub

Effects of Executing Macro Example to Clear Cell

The following images illustrate the results of executing the macro example.

  • Before macro execution: Cells A5 to C9 contain the string “data”, have a light blue fill, and the font is formatted as bold.

    Cells with data, fill color and bold formatting

  • After macro execution: Cells A5 to C9 (including both data and formatting) are cleared.

    Cells with cleared data and formatting

#2: Clear Cell Contents and Keep Formatting

VBA Code to Clear Cell Contents and Keep Formatting

To clear cell contents (but not formatting) using VBA, use a statement with the following structure:

Cells.ClearContents

Process Followed by VBA to Clear Cell Contents and Keep Formatting

Identify cells to clear > clear cell contents but keep formatting

VBA Statement Explanation

  1. Item: Cells.
    • VBA Construct: Range object.
    • Description: Range object representing the cells where you want to clear the contents but not the formatting.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset, Range.Resize or Application.ActiveCell properties. If you explicitly declare an object variable to represent Cells, use the Range object data type.

  2. Item: ClearContents.
    • VBA Construct: Range.ClearContents method.
    • Description: The Range.ClearContents method clears values and formulas from the Range object you specify (Cells). Range.ClearContents leaves formatting intact.

Macro Example to Clear Cell Contents and Keep Formatting

The following macro example clears the contents (but not the formatting) of cells A10 to C14 (myRange) in the worksheet named “Clear Cell” of the workbook containing the macro (ThisWorkbook).

Sub clearCellContentsKeepFormatting()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-clear-cell/

    'declare object variable to hold reference to cells to clear contents but not formatting
    Dim myRange As Range

    'identify cells to clear contents and keep formatting
    Set myRange = ThisWorkbook.Worksheets("Clear Cell").Range("A10:C14")

    'clear cell contents (but not formatting)
    myRange.ClearContents

End Sub

Effects of Executing Macro Example to Clear Cell Contents and Keep Formatting

The following images illustrate the results of executing the macro example.

  • Before macro execution: Cells A10 to C14 contain the string “data”, have a light gold fill, and the font is formatted as bold.

    Cells with data, interior fill and bold formatting

  • After macro execution: Cell contents of cells A10 to C14 are cleared. The formatting is kept.

    Cells with interior fill and bold formatting

#3: Clear Cell Formatting

VBA Code to Clear Cell Formatting

To clear cell formatting using VBA, use a statement with the following structure:

Cells.ClearFormats

Process Followed by VBA to Clear Cell Formatting

Identify cells to clear > clear cell formatting

VBA Statement Explanation

  1. Item: Cells.
    • VBA Construct: Range object.
    • Description: Range object representing the cells where you want to clear cell formatting.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset, Range.Resize or Application.ActiveCell properties. If you explicitly declare an object variable to represent Cells, use the Range object data type.

  2. Item: ClearFormats.
    • VBA Construct: Range.ClearFormats method.
    • Description: The Range.ClearFormats method clears the formatting of the Range object you specify (Cells). Range.ClearFormats doesn’t clear values or formulas.

Macro Example to Clear Cell Formatting

The following macro clears the cell formatting of cells A15 to C19 (myRange) of the worksheet named “Clear Cell” in the workbook containing the macro (ThisWorkbook).

Sub clearCellFormatting()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-clear-cell/

    'declare object variable to hold reference to cells to clear formatting
    Dim myRange As Range

    'identify cells to clear formatting
    Set myRange = ThisWorkbook.Worksheets("Clear Cell").Range("A15:C19")

    'clear cell formatting
    myRange.ClearFormats

End Sub

Effects of Executing Macro Example to Clear Cell Formatting

The following images illustrate the results of executing the macro example.

  • Before macro execution: Cells A15 to C19 contain the string “data”, have a light green fill, and the font is formatted as bold.

    Cells with data, interior fill and bold formatting

  • After macro execution: The formatting of cells A15 to C19 is cleared.

    Cells with data but cleared formatting

#4: Clear Cell Color

VBA Code to Clear Cell Color

To clear cell color using VBA, use a statement with the following structure:

Cells.Interior.Color = xlColorIndexNone

Process Followed by VBA to Clear Cell Color

Identify cells to clear > set interior color of cells to no color

VBA Statement Explanation

  1. Item: Cells.
    • VBA Construct: Range object.
    • Description: Range object representing the cells where you want to clear cell formatting.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset, Range.Resize or Application.ActiveCell properties. If you explicitly declare an object variable to represent Cells, use the Range object data type.

  2. Item: Interior.
    • VBA Construct: Range.Interior property and Interior object.
    • Description: The Range. Interior property returns an Interior object representing the interior of the cell range you specify (Cells).
  3. Item: Color.
    • VBA Construct: Interior.Color property.
    • Description: The Interior.Color property allows you to set the primary color of the cell interior represented by the Interior object returned by Range.Interior.
  4. Item: =.
    • VBA Construct: Assignment operator.
    • Description: The assignment operator assigns the xlColorIndexNone value to the Interior.Color property.
  5. Item: xlColorIndexNone.
    • VBA Construct: xlColorIndexNone constant.
    • Description: The xlColorIndexNone constant specifies that the color of the Interior object representing the interior of Cells is none.

Macro Example to Clear Cell Color

The following macro clears the cell color of cells A20 to C24 (myRange) in the worksheet named “Clear Cell” of the workbook containing the macro (ThisWorkbook).

Sub clearCellColor()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-clear-cell/

    'declare object variable to hold reference to cells to clear cell color
    Dim myRange As Range

    'identify cells to clear cell color
    Set myRange = ThisWorkbook.Worksheets("Clear Cell").Range("A20:C24")

    'clear cell color
    myRange.Interior.Color = xlColorIndexNone

End Sub

Effects of Executing Macro Example to Clear Cell Color

The following images illustrate the results of executing the macro example.

  • Before macro execution: Cells A20 to C24 contain the string “data”, have a light orange fill, and the font is formatted as bold.

    Cells with data, interior fill and bold formatting

  • After macro execution: The fill color of cells A20 to C24 is cleared.

    Cells with data and bold formatting, but no cell fill color

#5: Clear Cells with Zero

VBA Code to Clear Cells with Zero

To clear cells with zero within a cell range using VBA, use a macro with the following statement structure:

For Each Cell In Range
    If Cell.Value = myValue Then Cell.Clear
Next Cell

Process Followed by VBA to Clear Cells with Zero

Identify cell range > loop through cells > identify cells with zero > clear cell

VBA Statement Explanation

Lines #1 and #3: For Each Cell In Range | Next Cell

  1. Item: For Each… In… Next.
    • VBA Construct: For Each… Next statement.
    • Description: The For Each… Next statement repeats the statement within the loop (line #2) for each element (Cell) in the cell range (Range) you want to search for zeroes in.
  2. Item: Cell.
    • VBA Construct: Element of the For Each… Next statement and object variable of the Range object data type.
    • Description: The Element of the For Each… Next statement is an object variable used to iterate through the elements (Cell) of the cell range (Range) you want to search for zeroes in.

      If you explicitly declare an object variable to represent Cell, use the Range object data type.

  3. Item: Range.
    • VBA Construct: Group of the For Each… Next statement and Range object.
    • Description: The For Each… Next statement repeats the statements within the loop (line #2) for each element (Cell) in the Group (Range). Range is a Range object representing the cells where you want to search for zeroes.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset, Range.Resize or Application.ActiveCell properties. If you explicitly declare an object variable to represent Range, use the Range object data type.

Line #2: If Cell.Value = myValue Then Cell.Clear

  1. Item: If… Then.
    • VBA Construct: If… Then… Else statement.
    • Description: The If… Then… Else statement conditionally executes a group of statements depending on the value of an expression. For these purposes:
      • The If… Then… Else statement tests the specified condition (Cell.Value = myValue).
      • If the condition is met and returns True: Cell.Clear is executed.
      • If the condition is not met and returns False: Execution continues with the statement following the If… Then… Else statement (Next Cell).
  2. Item: Cell.
    • VBA Construct: Object variable of the Range object data type.
    • Description: Cell is an object variable used to iterate through the elements of the cell range (Range) you want to search for zeroes in. Within the If… Then… Else statement, Cell represents the individual cell the For Each… Next loop is currently iterating through.

      If you explicitly declare an object variable to represent Cell, use the Range object data type.

  3. Item: Value.
    • VBA Construct: Range.Value property.
    • Description: The Range.Value property returns the value in the cell the For Each…Next loop is currently iterating through.
  4. Item: myValue.
    • VBA Construct: Variable of a numeric data type.
    • Description: myValue represents the value you want to search for and use to determine which cells to clear. Within the macro structure used in this VBA Tutorial, myValue is 0 (zero).

      If you explicitly declare a variable to represent myValue, use a numeric data type such as Long, Single or Double (depending on the value you’re searching for).

  5. Item: Cell.Value = myValue.
    • VBA Construct: Condition of If… Then… Else statement.
    • Description: This condition is an expression that evaluates to True or False. Cell.Value = myValue returns True or False, as follows:
      • True: Value of Cell is equal to myValue (zero).
      • False: Value of Cell isn’t equal to myValue (zero).
  6. Item: Clear.
    • VBA Construct: Range.Clear method.
    • Description: The Range.Clear method clears the cell the For Each… Next loop is currently iterating through. Range.Clear clears the entire Range object, including values, formulas and formatting.

      If you don’t want to clear the entire Range object, but only its contents, formatting or cell color, please refer to the appropriate sections above.

Macro Example to Clear Cells with Zero

The following macro example clears the cells with zero (0) in cells A25 to C29 (myRange) in the worksheet named “Clear Cell” of the workbook containing the macro (ThisWorkbook).

Sub clearCellsWithZero()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-clear-cell/

    'declare object variables to hold references to cell range where you search for zeroes
    Dim myRange As Range

    'declare object variable used to iterate through the elements of the cell range
    Dim iCell As Range

    'declare variable to hold value (zero) you search for
    Dim myValue As Long

    'identify cells to search for zeroes
    Set myRange = ThisWorkbook.Worksheets("Clear Cell").Range("A25:C29")

    'set value (zero) to search for
    myValue = 0

    'loop through each cell (iCell) of the cell range (myRange)
    For Each iCell In myRange

        'test if value is zero. If condition is met, clear cell
        If iCell.Value = myValue Then iCell.Clear

    Next iCell

End Sub

Effects of Executing Macro Example to Clear Cells with Zero

The following images illustrate the results of executing the macro example.

  • Before macro execution: Cells A25 to C29 contain the string “data” or the value zero (0), have a light gray fill, and the font is formatted as bold.

    Cells with data and zero, fill color and bold formatting

  • After macro execution: Cells between A25 to C29 containing a zero (0) are cleared (including both data and formatting).

    Some cells with data, fill color and bold formatting

References to VBA Constructs Used in this VBA Tutorial

Use the following links to visit the appropriate webpage in the Microsoft Developer Network:

  1. Identify the workbook and worksheet where the cells to clear are located:
    • Workbook object.
    • Application.ActiveWorkbook property.
    • Application.ThisWorkbook property.
    • Application.Workbooks property.
    • Worksheet object.
    • Application.ActiveSheet property.
    • Workbook.Worksheets property.
  2. Identify the cells to clear:
    • Range object.
    • Worksheet.Range property.
    • Worksheet.Cells property.
    • Application.ActiveCell property.
    • Application.Selection property.
    • Range.Range property.
    • Range.Cells property.
    • Range.Item property.
    • Range.Offset property.
    • Range.Resize property.
    • For Each… Next statement.
    • If… Then… Else statement.
    • Range.Value property.
  3. Clear cells:
    • Range.Clear method.
    • Range.ClearContents method.
    • Range.ClearFormats method.
    • Interior object.
    • Range.Interior property.
    • Interior.Color property.
    • xlColorIndex enumeration.
  4. Work with variables and data types:
    • Dim statement.
    • Set statement.
    • = operator.
    • Data types:
      • Double data type.
      • Long data type.
      • Single data type.

Skip to content

Clear Cells in Excel Range Worksheet using VBA

Home » Excel VBA » Clear Cells in Excel Range Worksheet using VBA

Description:

Most of the times we clear the data from a cells or a range and re-enter to do some calculations. For examples we may have some template to enter data and calculate the tax. We may want to do this for all the employees of an organization. In this case we need to Clear data Excel from a Range in Worksheet using VBA before entering the data for each employee

Clear Cells in Excel of a range or Worksheet using VBA- Solution(s):

Copy Data from One Range to Another in Excel VBAWe can clear Cells or a Range using Clear Method OR ClearContents Method of a Range or Cell. Clear will Clear the data and Formats of the given Range or Cells. And ClearContents will clear only the data, will not clear any formats.

Clear Cells Range data in Excel Worksheet using VBA – An Example

The following examples will show you how clear the data of Cells, Range or entire worksheet using Clear and ClearContents Methods.

Clearing a Cells/Range using Clear Method

This method will clear the range of cells including Formats:

Sub sbClearCells()
Range("A1:C10").Clear
End Sub
Clearing Only Data of a Range using ClearContents Method

This method will clear only clear the content or data of the range not formats (Formats remain same)

Sub sbClearCellsOnlyData()
Range("A1:C10").ClearContents
End Sub
Clearing Entire Worksheet using Clear Method

This method will clear entire worksheet including formats.

Sub sbClearEntireSheet()
Sheets("SheetName").Cells.Clear
End Sub
Clearing Only Data from Worksheet using ClearContents Method

This method will clear only data of worksheet, not formats.

Sub sbClearEntireSheetOnlyData()
Sheets("SheetName").Cells.ClearContents
End Sub
Instructions:
  1. Open an excel workbook
  2. Enter some data in Sheet1 at A1:C10
  3. Press Alt+F11 to open VBA Editor
  4. Insert a Module for Insert Menu
  5. Copy the above code and Paste in the code window
  6. Save the file as macro enabled workbook
  7. Press F5 to run it
Conclusion:

Both Clear and ClearContents are useful based on your requirement. If you want to Clear only the Content, use ClearContent method. If you want Clear everything (Content and Formats), use Clear method.

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

Related Posts

    • Description:
    • Clear Cells in Excel of a range or Worksheet using VBA- Solution(s):

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

28 Comments

  1. Dave
    July 13, 2013 at 10:53 PM — Reply

    Please note that there is a typo in your code above; ClearContents is used for both examples.

    The first instance should read:
    Range(“A1:C10”).Clear

    The second instance is correct as:
    Range(“A1:C10”).ClearContents

  2. PNRao
    July 13, 2013 at 11:01 PM — Reply

    Thanks Dave! Corrected it!

    Regards,
    PNRao

  3. Felipe
    March 11, 2015 at 11:54 AM — Reply

    Hi!
    I want to erase some of the contents but not all from cells. For example in every cell I have several qualifiers with an specific value, something like /qualifier1=value2 /qualifier2=value2 etc. I just want to erase all qualifiers but number 1. Is this possible?

    Thank you in advance!

  4. PNRao
    March 21, 2015 at 2:38 PM — Reply

    Hi Felipe,
    There is no direct method/finction to do this task. You can write a formula or VBA procedure to do this.

    Thanks-PNRao!

  5. Dushyant
    July 8, 2015 at 11:12 AM — Reply

    hello sir

    Can we clear excel data of two excel sheet of specific cell’s in one code

    e.g. i have two excel sheet in my workbook A and B and i wont clear data of specific cell using range option (A3:B10) for Sheet A and (C2:D10) for sheet B, i want this operation in One code only
    can you please help me

    Regards

    Dushyant Padhya

  6. PNRao
    July 8, 2015 at 5:30 PM — Reply

    If you want clear multiple ranges from a sheet with one single clear statements, you can use the below method:

    Sheets("SheetA").Range("A3:B10", "C2:D10").Clear
    

    If I am correct, you want to put tow statements in one single statement:
    Below is the code to clear the two ranges:

    Sheets("SheetA").Range("A3:B10").Clear
    Sheets("SheetB").Range("C2:D10").Clear
    

    You can use “:” to concatenate the VBA statements

    Sheets("SheetA").Range("A3:B10").Clear: Sheets("SheetB").Range("C2:D10").Clear
    

    Hope this hellps!
    Thanks-PNRao

  7. james
    August 7, 2015 at 7:43 PM — Reply

    I have a list where some cell values begin with a letter and some with a number. How can I use the clear function to clear cells beginning with a letter but leave those beginning with a number? All cells contain both letters and number, but I want to clear those where the letter is the first character. also some are uppercase and some lowercase (not sure if this matters)
    thanks

    James

  8. PNRao
    August 7, 2015 at 7:57 PM — Reply

    Hi James,

    The below macro checks for the first character of each cell in a given range, and clears if it is non-numeric:

    Sub sbClearCellsIFCritera()
    
    Set Rng = Range("F1:F20") ' change this range as per your requirement
    For Each cell In Rng.Cells
        If IsNumeric(Left(cell, 1)) = False Then
            cell.Clear
        End If
    Next
    
    End Sub
    

    Thanks-PNRao

  9. ravindra
    August 22, 2015 at 10:40 PM — Reply

    I want to get the data from one workbook to another workbook by using VBA coding. So could you please help me.

  10. PNRao
    August 23, 2015 at 2:10 AM — Reply

    Hi Ravindra,
    You can use the Copy command as shown below:

    Workbooks("Book1").Sheets("Sheet1").Range("A1:B10").Copy _
    Destination:=Workbooks("Book2").Sheets("Sheet1").Range("E1")
    

    Thanks-PNRao!

  11. Brad Bouchaud
    November 6, 2015 at 7:47 AM — Reply

    Hi and thanks in advance.
    I have a List of 3 items per row in a Worksheet with 30 such rows and a button besides each to run a Macro to clear the contents when required.
    Other macros perform functions on the data in the lists.
    Unfortunately I am using the .ActiveCell which doesn’t seem to detect I am in the Cell with the button but is uses the last cell I was in, any ideas on how I can clear the contents of the 3 cells beside the buttons without writing 30 different macros?

  12. Kyle Minnett
    March 2, 2016 at 1:34 AM — Reply

    If I want to clear a variable range of cells based on a specific input how would I do this?

    for example lets say i am running a code that fills cells e5:e10 based on an input variable that i have chosen. then i decide that i want to change that input variable and by changing it my data range runs from cell e5:e9. however because i just ran a calculation that created a range from e5:e10 the value in cell e10 is still present with the new range ( i want to the contents in cell e10 to be cleared)….i hope this wasn’t too confusing.

  13. Venkata Naidu M
    May 31, 2016 at 12:38 PM — Reply

    I want to clear the data without formulas from active worksheet

    Please help…

  14. PNRao
    June 4, 2016 at 9:44 PM — Reply

    Hi Venkat, You can use Activesheet.Cells.Clear Method to clear the entire sheet (Activesheet).

    Thanks-PNRao!

  15. Anas Ahmad
    July 19, 2016 at 12:34 PM — Reply

    Hello Everybody,

    I want clear particular range of data from cells.

    For example: Cells which have only zero and the value above 5000 from the whole sheet.

    Can u suggest me how to give coding.

  16. ASAD
    August 12, 2016 at 5:38 PM — Reply

    how to use check box to clear and unclear cell

  17. PNRao
    August 14, 2016 at 11:35 PM — Reply

    We can use .Clear Method to clear the Cells but, we can do not have the method to undo /unclear the cleared cells:
    The below Code will clear when you select the check box.

    Private Sub CheckBox1_Click()
    If CheckBox1.Value = True Then
        Cells.Clear
    End If
    End Sub
    

    Thanks-PNRao!

  18. Pranav Roy
    October 28, 2016 at 10:32 PM — Reply

    Hi..
    I’m new to macro programming
    How to write a macro with relative refrences which can clear/clear contents after a particular cell. That is if a cell is chosen and macro is started it should delete the values or formats for the given no ( say 12) cells .May be row or columnwise.

  19. Donna
    November 2, 2016 at 6:40 PM — Reply

    I have one workbook with several sheets, (more than 200 sheets) and I would like to clear contents within specific cells (same on all sheets) in workbook. How can I do that each sheet is named with last 4 digits of each VIN.
    What code would I use?

  20. srinivas
    January 7, 2017 at 5:11 PM — Reply

    hi
    I want to this macro code
    one excel sheet first cell to six cells type “p” letter then seventh cell automatic display “wp”
    please tell me this vba code

  21. Himani
    January 10, 2017 at 4:12 PM — Reply

    Hi,
    Is there any way to clear data of selective rows from multiple sheets keeping the formatting and formula same??

    Thanks
    Himani

  22. paige
    January 11, 2017 at 10:49 AM — Reply

    Hi Anas,
    I have the exact same query – it’s very tricky.
    did you end up finding a solution?

    Thank you PNRao for everything thus far!

  23. April
    January 25, 2017 at 5:34 PM — Reply

    I want to clear the values that are returned in a range of cells but, I want to keep the formula that was entered in the cells. Is there a way to do that?

  24. Nasiba
    February 17, 2017 at 12:56 AM — Reply

    Hello,

    How can I clear content of multiple tabs? For example I need to clear Range(“A:N”) columns from 5 different worksheets

  25. Yaried
    May 29, 2017 at 2:27 AM — Reply

    hi every body I do have a excel template, and I do have a program for clearing data but I also want to add an option whether to clean the data , ie yes no option if the user press the no button the data will not be cleared can u tell me a command for that case. could you pleas send me a mail
    thanks for your cooperation

  26. Chittaranjan
    June 20, 2017 at 4:52 PM — Reply

    Hello All,

    Need help on one thing, Whenever i open Excel which containing macro an error occurs as “Security Warning Macro have been Disable. Enable Content” . After clicking on Enable content button the excel open in good manner.
    Now I have to disable any cell value or change color to while, let say cell F5 having text “Best of Luck” which is in black color. I record the macro as to change it to white color/it should be disabled. OK.

    My Question is, whenever we click on Enable content button, the text color “Best of Luck” of cell F5 should be change to white/ disappear.

    So How to do, need help.

  27. Veasna
    December 27, 2017 at 2:23 PM — Reply

    Hello Dear,

    I need some help from you. I want to delete entire sheet content.But only content that filled up not content that created by formula.

  28. Jospeh
    May 11, 2020 at 10:08 PM — Reply

    I need to figure out how to clear a set of rows underneath my header row. e.g. HeaderRow+1, (Don’t know what to put here). Clear Contents.

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

 

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

  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

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

Сообщений: 23251
Регистрация: 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 — каморка  
клозет — устар. помещение для отправления естественных надобностей

 

Юрий М

Модератор

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

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

#9

09.07.2012 09:52:32

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

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

We perform many actions in Excel like cutting, copying, pasting, adding, deleting, and inserting regularly. We can use all of these actions using VBA coding. However, one of the important concepts we need to learn in VBA is the “deleting column.” This article will show you how to use this “Delete Column” option in VBA.

Table of contents
  • Excel VBA Delete Column
    • What Does Delete Column Do in Excel VBA?
    • Examples of Excel VBA Delete Column Method
      • Example #1 – Using Delete Method
      • Example #2 – Delete Columns with Worksheet Name
      • Example #3 – Delete Blank Columns
      • Example #4 – Delete Blank Cells Columns
    • Recommended Articles

What Does Delete Column Do in Excel VBA?

As the name says, it will delete the specified column. To perform this task, we must first identify which column to delete. The selection of deleted columns differs from one scenario to another, so that we will cover some of the important and often faced scenarios in this article.

Deleting the columns is easy. First, we need to use the COLUMNS property to select the column, so VBA’s syntax of the “Delete Column” method is below.

Columns (Column Reference).Delete

So, we can construct the code like this:

Columns (2).Delete or Columns (“B”).Delete

It will delete column number 2, i.e., column B.

If we want to delete multiple columns, we cannot enter columns. Instead, we need to reference the columns by column headers, i.e., alphabets.

Columns (“A:D”).Delete

It will delete the column from A to D, i.e., the first 4 columns.

Like this, we can use the “Delete Column” method in VBA to delete particular columns. In the below section, we will see more examples to understand it better. Read on.

VBA Delete Column

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

Examples of Excel VBA Delete Column Method

Below are examples of deleting columns using VBA.

Example #1 – Using Delete Method

Assume you have the datasheet, something like the below.

VBA Delete Column Example 1

If we want to delete the month “Mar,” first select the column property.

Code:

Sub Delete_Example1()

  Columns(

End Sub

VBA Delete Column Example 1-1

Mention the column number or alphabet. In this case, it is either 3 or C.

Code:

Sub Delete_Example1()

  Columns(3).

End Sub

VBA Delete Column Example 1-2

Use the Delete method.

Note: You would not get the IntelliSense list to select the Delete method. Just type “Delete.”

Code:

Sub Delete_Example1()

  Columns(3).Delete

End Sub

VBA Delete Column Example 1-3

Or you can enter the column address like this.

Code:

Sub Delete_Example1()

  Columns("C").Delete

End Sub

VBA Delete Column Example 1-4

Run this code using the F5 key, or you can run it manually and see the result.

VBA Delete Column Example 1-5

Both the codes will do the same job of deleting the mentioned column.

VBA Delete Column Example 1-6

If we want to delete multiple columns, we need to mention them in the alphabet. We cannot use column numbers here.

If we want to delete columns 2 to 4, we can pass the code like the below.

Code:

Sub Delete_Example1()

  Columns("C:D").Delete

End Sub

VBA Delete Column Example 1-7

Run this code manually through the run option or press the F5 key. It will delete the columns “Feb,” “Mar,” and “Apr.”

VBA Delete Column Example 1-8

Example #2 – Delete Columns with Worksheet Name

The above is an overview of how to delete columns using VBA code. However, that is not a good practice to delete columns. Deleting the column without referring to the worksheet name is dangerous.

If you have not mentioned the worksheet name, then whichever sheet is active will delete columns of that sheet.

First, we need to select the worksheet by its name.

Code:

Sub Delete_Example2()

    Worksheets("Sales Sheet").Select

End Sub

VBA Delete Column Example 2

After selecting the sheet, we need to select the columns. We can also select the columns by using the VBA RANGE objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more.

Code:

Sub Delete_Example2()

   Worksheets("Sales Sheet").Select
   Range("B:D").Delete

End Sub

VBA Delete Column Example 2-1

It will delete columns B to D of the worksheet “Sales Sheet.” For this code, it does not matter which is active. Still, it will delete the mentioned columns of that sheet only.

We can construct the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more in the single line itself.

Code:

Sub Delete_Example2()

    Worksheets("Sales Sheet").Range("B:D").Delete

End Sub

VBA Delete Column Example 2-2

It also deletes the columns “B to D” without selecting the worksheet “Sales Sheet.”

Example #3 – Delete Blank Columns

Assume you have data that has alternative blank columns like the below.

VBA DC Example 3

So, delete every alternate column. Then, we can use the below code.

Code:

Sub Delete_Example3()

    Dim k As Integer

    For k = 1 To 4
    Columns(k + 1).Delete
    Next k

End Sub

VBA DC Example 3-1

Run this code using the F5 key or manually. Then, it will delete all the alternative blank columns, and our data will look like this.

VBA Delete Column Example 3-2

Note: This works only for alternative blank columns.

Example #4 – Delete Blank Cells Columns

Now, look at this example. In certain situations, we need to delete the entire column if we find any blank cells in the data range. Consider the below data for an example.

VBA DC Example 4

All the yellow-colored cells are blank. So here, we require to delete all the blank cell columns. The below code will do that.

Code:

Sub Delete_Example4()

    Range("A1:F9").Select

    Selection.SpecialCells(xlCellTypeBlanks).Select

    Selection.EntireColumn.Delete

End Sub

VBA DC Example 4-1

Let me explain this code line by line for you.

Our data is from A1 to F9, so first, we must select that range. The below code will do that.

Range("A1:F9").Select

We need to select the blank cells in this selected range of cells. So, to select a blank cell, we need a special cell property. In that property, we have used cell type as blank.

Selection.SpecialCells(xlCellTypeBlanks).Select

Next, it will select all the blank cells, and we are deleting the entire selection column in the selection.

Selection.EntireColumn.Delete

So, our result will look like this.

VBA DC Example 4-2

Wherever it has found the blank cell, it has deleted those blank cells entirely.

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

Recommended Articles

This article has been a guide to VBA Delete Column. Here, we learn four methods to delete columns using Excel VBA code, practical examples, and downloadable codes. Below are some useful Excel articles related to VBA: –

  • How to Delete File in VBA?
  • VBA Integer Function
  • IsEmpty Function in VBA
  • IFERROR in VBA

Home / VBA / VBA ClearContents (from a Cell, Range, or Entire Worksheet)

Written by Puneet for Excel 2007, Excel 2010, Excel 2013, Excel 2016, Excel 2019, Excel for Mac

Key Points

  • To clear content from a cell, you need to use the ClearContents method.
  • You can use it for a single cell, a range, or an entire worksheet.

ClearContents Method

In VBA, there is a method called ClearContents that you can use to clear values and formulas from a cell, range of cells, and the entire worksheet.

Expression.ClearContents

To use this method, first, you need to define the expression somewhere you want to clear the content, and then type “.ClearContents”.

Clear Contents from a Single Cell

Let’s say you want to clear values from cell A1. First, you need to define cell A1 using the range object and then the ClearContents method.

So the code would be:

Sub ClearContentExamples()
Range("A1").ClearContents
End Sub

You can also use the cells property to define a cell and the code would be:

Sub ClearContentExamples()
Cells(1, 1).ClearContents
End Sub

Clear Contents from a Range

In the same way, you can define a range and then use the ClearContent method to clear values and formulas from that range. Let’s say you want to clear values from the range A1:A10, in this case, the code would be something like the below.

Sub ClearContentExamples()
Range("A1:A10").ClearContents
End Sub

Clear Content from an Entire Worksheet

To clear content from an entire worksheet, you can use the below code:

Sub ClearContentExamples()
Cells.ClearContents
End Sub

And to clear from a specific worksheet:

Worksheets("Sheet1").Cells.ClearContents

Clear Content from the Selection

If you want to write a dynamic code that can clear contents from the selected cells, then you can use the below code.

Sub ClearContentExamples()
    Selection.ClearContents
End Sub

Other Methods

Below are some of the other methods that you can use:

Sub ClearContentExamples()
    Range(“A1”).Clear ‘Clears Everything   
    Range(“A1”).ClearComments ‘Clear Comments  
    Range(“A1”).ClearFormats ‘Clears Formatting   
    Range(“A1”).ClearHyperlinks ‘Clear Hyperlinks  
    Range(“A1”).ClearNotes ‘Clear Notes
    Range(“A1”).ClearOutline ‘Clears Outline
End Sub

More Tutorials

    • Count Rows using VBA in Excel
    • Excel VBA Font (Color, Size, Type, and Bold)
    • Excel VBA Hide and Unhide a Column or a Row
    • Excel VBA Range – Working with Range and Cells in VBA
    • Apply Borders on a Cell using VBA in Excel
    • Find Last Row, Column, and Cell using VBA in Excel
    • Insert a Row using VBA in Excel
    • Merge Cells in Excel using a VBA Code
    • Select a Range/Cell using VBA in Excel
    • SELECT ALL the Cells in a Worksheet using a VBA Code
    • ActiveCell in VBA in Excel
    • Special Cells Method in VBA in Excel
    • UsedRange Property in VBA in Excel
    • VBA AutoFit (Rows, Column, or the Entire Worksheet)
    • VBA Copy Range to Another Sheet + Workbook
    • VBA Enter Value in a Cell (Set, Get and Change)
    • VBA Insert Column (Single and Multiple)
    • VBA Named Range | (Static + from Selection + Dynamic)
    • VBA Range Offset
    • VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
    • VBA Wrap Text (Cell, Range, and Entire Worksheet)
    • VBA Check IF a Cell is Empty + Multiple Cells

    ⇠ Back to What is VBA in Excel

    Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes

    Like this post? Please share to your friends:
  • Vba excel очистить диапазон ячеек на листе
  • Vba excel очистить все фильтры
  • Vba excel очистить весь лист
  • Vba excel оформление ячейки
  • Vba excel оформление ячеек