Excel clearcontents что это

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

    Содержание

    1. Методы объекта Range
    2. Метод Activate
    3. Метод ClearContents
    4. Метод ClearFormats
    5. Метод Сору
    6. Метод Delete
    7. Метод FillDown
    8. Методы FillUp, FillLeft, FillRight
    9. Метод Insert
    10. Метод Merge
    11. Метод Select
    12. Метод UnMerge
    13. VBA Excel. Range.Clear и другие методы очистки ячеек
    14. Методы очистки ячеек
    15. Примеры использования
    16. 6 комментариев для “VBA Excel. Range.Clear и другие методы очистки ячеек”
    17. VBA Excel. Ячейки (обращение, запись, чтение, очистка)
    18. Обращение к ячейке по адресу
    19. Обращение к ячейке по индексу
    20. Обращение к ячейке по имени
    21. Запись информации в ячейку
    22. VBA Clear Contents
    23. Excel VBA Clear Contents
    24. What are Clear Contents in Excel VBA?
    25. Difference Between Clear & Delete Methods
    26. Use VBA Clear Contents Method to Retain Formatting of Cells
    27. Loop Through all the Worksheets and Clear Contents of Specific Range
    28. Recommended Articles

    Методы объекта Range

    Рассмотрим некоторые основные методы объекта Range.

    Метод Activate

    Метод Activate задает активную ячейку в выделенном диапазоне ячеек (для выделения ячейки следует использовать метод Select объекта Range). Например, если объект Range представляет диапазон ячеек А1:С5, то результатом выполнения приведенных ниже инструкций будет активизация ячейки С1:

    Метод ClearContents

    Метод ClearContents очищает формулы и значения, содержащиеся в ячейках, представляемых объектом Range. Данный метод очищает только содержимое ячеек, сохраняя их форматирование.

    Метод ClearFormats

    Метод ClearFormats удаляет все форматирование ячеек, не воздействуя при этом на хранящиеся в них данные.

    Метод Сору

    Метод Сору позволяет скопировать содержимое ячеек в буфер обмена.

    Метод Delete

    Метод Delete удаляет ячейки, определяемые объектом Range. Синтаксис этого метода:

    Элементы синтаксиса метода Delete представлены в табл.15.

    Элемент Описание
    Expression Выражение, возвращающее объект Range
    Shift Необязательный параметр типа Variant. Этот параметр задает механизм сдвига ячеек в процессе замены удаленных ячеек. Его значение может равняться значению одной из двух констант: xiShiftToLeft или xlShiftUp. Если аргумент Shift отсутствует, то MS Excel определяет способ сдвига ячеек в зависимости от формы диапазона

    Таблица 15. Элементы синтаксиса метода Delete

    Метод FillDown

    Метод FillDown предназначен для распространения содержимого и форматирования ячейки (или ячеек) из верхней строки диапазона в остальные строки диапазона. Действия, выполняемые данным методом, аналогичны действиям, выполняемым с помощью интерфейса пользователя при распространении содержимого ячейки с использованием мыши.

    Ниже представлен пример, который позволяет заполнить все ячейки диапазона С1:С5 содержимым ячейки С1:

    Методы FillUp, FillLeft, FillRight

    Методы FillUp, FillLeft, FillRight выполняют действия, аналогичные действиям, выполняемым методом FillDown. Отличие состоит в том, что метод FillUp копирует ячейки, содержащиеся в нижней строке диапазона, метод FillLeft копирует ячейки, содержащиеся в крайнем правом столбце диапазона, а метод FillRight – в крайнем левом столбце.

    Метод Insert

    Метод Insert позволяет вставить ячейку или диапазон ячеек в рабочий лист. При вставке другие ячейки сдвигаются одним из способов, который определяется аргументом Shift. Синтаксис метода Insert:

    Элементы синтаксиса метода Insert представлены в табл. 16.

    Элемент Описание
    Expression Выражение, возвращающее объект Range
    Shift Необязательный параметр типа Variant. Предназначен для определения способа сдвига ячеек. Значение данного параметра может быть равно одной из двух констант: xlShiftToRight (ячейки сдвигаются вправо) или xlShiftDown (ячейки сдвигаются вниз).
    Если этот аргумент отсутствует, то MS Excel определяет способ сдвига в зависимости от формы диапазона

    Таблица 16. Элементы синтаксиса метода Insert

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

    Здесь выполняется добавление новых ячеек в диапазон ячеек A1:D15. При этом ячейки диапазона сдвигаются вниз.

    Метод Merge

    Метод Merge позволяет объединить несколько ячеек в одну. При этом в качестве объединяемых используются ячейки, определяемые объектом Range. Синтаксис этого метода:

    Элементы синтаксиса метода Merge описаны в табл. 17.

    Элемент Описание
    Expression Выражение, возвращающее объект Range
    Across Необязательный параметр типа Variant. Если данный параметр имеет значение True, то ячейки в каждой строке диапазона объединяются как раздельные объединенные ячейки. В противном случае (False) все ячейки диапазона объединяются в одну ячейку

    Таблица 17. Элементы синтаксиса метода Merge

    Примечание:

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

    Метод Select

    Метод Select позволяет выделить ячейки, определяемые объектом Range. Ниже в качестве примера приведена инструкция, реализующая выделение диапазона ячеек C1:F5:

    Метод UnMerge

    Метод UnMerge разбивает объединенную ячейку на отдельные ячейки (чтобы узнать, является ли ячейка результатом объединения нескольких ячеек, используйте свойство MergeCells).

    Источник

    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 Excel. Ячейки (обращение, запись, чтение, очистка)

    Обращение к ячейке на листе Excel из кода VBA по адресу, индексу и имени. Чтение информации из ячейки. Очистка значения ячейки. Метод ClearContents объекта Range.

    Обращение к ячейке по адресу

    Допустим, у нас есть два открытых файла: «Книга1» и «Книга2», причем, файл «Книга1» активен и в нем находится исполняемый код VBA.

    В общем случае при обращении к ячейке неактивной рабочей книги «Книга2» из кода файла «Книга1» прописывается полный путь:

    Удобнее обращаться к ячейке через свойство рабочего листа Cells(номер строки, номер столбца), так как вместо номеров строк и столбцов можно использовать переменные. Обратите внимание, что при обращении к любой рабочей книге, она должна быть открыта, иначе произойдет ошибка. Закрытую книгу перед обращением к ней необходимо открыть.

    Теперь предположим, что у нас в активной книге «Книга1» активны «Лист1» и ячейка на нем «A1». Тогда обращение к ячейке «A1» можно записать следующим образом:

    Точно также можно обращаться и к другим ячейкам активного рабочего листа, кроме обращения ActiveCell, так как активной может быть только одна ячейка, в нашем примере – это ячейка «A1».

    Если мы обращаемся к ячейке на неактивном листе активной рабочей книги, тогда необходимо указать этот лист:

    Имя ярлыка может совпадать с основным именем листа. Увидеть эти имена можно в окне редактора VBA в проводнике проекта. Без скобок отображается основное имя листа, в скобках – имя ярлыка.

    Обращение к ячейке по индексу

    К ячейке на рабочем листе можно обращаться по ее индексу (порядковому номеру), который считается по расположению ячейки на листе слева-направо и сверху-вниз.

    Например, индекс ячеек в первой строке равен номеру столбца. Индекс ячеек во второй строке равен количеству ячеек в первой строке (которое равно общему количеству столбцов на листе, зависящему от версии Excel) плюс номер столбца. Индекс ячеек в третьей строке равен количеству ячеек в двух первых строках плюс номер столбца. И так далее.

    Для примера, Cells(4) та же ячейка, что и Cells(1, 4). Используется такое обозначение редко, тем более, что у разных версий Excel может быть разным количество столбцов и строк на рабочем листе.

    По индексу можно обращаться к ячейке не только на всем рабочем листе, но и в отдельном диапазоне. Нумерация ячеек осуществляется в пределах заданного диапазона по тому же правилу: слева-направо и сверху-вниз. Вот индексы ячеек диапазона Range(«A1:C3»):

    Обращение к ячейке Range(«A1:C3»).Cells(5) соответствует выражению Range(«B2») .

    Обращение к ячейке по имени

    Если ячейке на рабочем листе Excel присвоено имя (Формулы –> Присвоить имя), то обращаться к ней можно по присвоенному имени.

    Допустим одной из ячеек присвоено имя – «Итого», тогда обратиться к ней можно – Range(«Итого») .

    Запись информации в ячейку

    Содержание ячейки определяется ее свойством «Value», которое в VBA Excel является свойством по умолчанию и его можно явно не указывать. Записывается информация в ячейку при помощи оператора присваивания «=»:

    Источник

    VBA Clear Contents

    Excel VBA Clear Contents

    ClearContents is a method in VBA used to delete or remove the values stored in the cells provided to it. This method makes the cell range empty. It is used with the range property to access the specified cell range. An example of this method is range(“A1:B2”). The ClearContents method will clear the contents of cells from A1 to B2.

    In Excel, adding and deleting data is a common routine task.

    Sometimes we delete a single cell value, sometimes many cell values, and sometimes we may require to delete the entire worksheet content. This article will show you how to use the “ClearContents” method in Excel VBA. In VBA, we have many methods to do this, like “Clear,” “Delete,” and “Clear Contents.”

    Table of contents

    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 Clear Contents (wallstreetmojo.com)

    What are Clear Contents in Excel VBA?

    Before we tell you about ClearContents in VBA, let me show how we can delete or clear off the data in the specific range.

    Look at the below data.

    Code:

    After mentioning the range of cells by using the RANGE object, we need to select the method “Clear” to clear off the mention of the cell values.

    Code:

    It will clear off the mentioned cell values.

    Code:

    Apart from the clear method, we can also use the “DELETE” method.

    Code:

    It will delete the mentioned cell values, just like our clear method.

    Both the above codes will delete the entire worksheet “Sheet1” data. In addition, it will delete the cell values from the first cell to the last cell of the worksheet.

    If you want to delete the present sheet cells, you can use the Active Sheet object.

    Difference Between Clear & Delete Methods

    We know this question should have already played in your mind.

    However, there is a difference between these two methods.

    When you use the method “Delete,” it will delete the cell, and the below cell will take over the position of the deleted cell.

    For example, look at the below image.

    Now, we will use the delete method to delete cell A1.

    Code:

    We will run this code and see what happens.

    Look what happened here. As we said, when we deleted cell A1, it got deleted, but cell A2 moved one cell up and occupies the deleted cell. So, it will lead to a data mismatch. So, be careful while using the “Delete” method.

    Now, for the same data, we will clear the method.

    Code:

    Now, see what happens when we run this code.

    This code has just vacated cell A1 without altering other cells. Therefore, this looks like a proper method to delete only the part of the cells of the entire data range.

    Use VBA Clear Contents Method to Retain Formatting of Cells

    If you have observed the previous two methods, those two methods not only deleted or cleared off the cells provided. It also deleted the formatting of the cells we have provided.

    To retain the formatting of the cells, we need not use neither “Delete” nor “Clear,” but we need to use the VBA “ClearContents” method.

    When you enter the range of cells using a RANGE object, it will show all its properties and methods.

    We can access “Delete,” we can access “Clear,” and we can also access “ClearContents” methods.

    Select this method.

    Code:

    It will clear content from A1 to C3 cell, but we will have all the existing formatting.

    As you can see in the above picture, we have cell color in VBA, borders, and every formatting associated with those mentioned cells.

    Similarly, we can clear the contents of other sheets as well.

    It will clear the contents from cells A1 to D10 in sheet “Sheet1”.

    Similarly, we can delete the other open workbook cells as well.

    Loop Through all the Worksheets and Clear Contents of Specific Range

    The below code will do the job.

    Code:

    Note: You can change the range of cells as per your wish.

    If you want to clear off the entire worksheet data, then you need to use the code below.

    Code:

    You can download this VBA Clear Contents Excel template here – VBA Clear Contents Template.

    Recommended Articles

    This article has been a guide to VBA Clear Contents. Here, we learn how to use the Clear, Delete, and ClearContents method in VBA to clear data in Excel and some simple to advanced examples. Below are some useful Excel articles related to VBA: –

    Источник

    Метод 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 возвращают очищаемые свойства ячеек к значениям по умолчанию. К таким, как на вновь созданном стандартном рабочем листе. При любых методах очистки высота строк и ширина столбцов не изменяются.


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


    How to clear contents of Excel cells/range using VBA

    The ClearContents is an Excel function that can be used in VBA to remove values and formulas in the range.

    However, formatting and conditional formatting remain intact when using the ClearContents function.

    An example of removing the value of A2 cell

    Following sheet is used for our examples in this tutorial:

    Excel-clearcontent-cell

    We will remove the A2 cell value by using the ClearContents function as follows:

    Sub clear_content_ex()

    Range(«B3»).ClearContents

    End Sub

    Result:

    Excel-clearcontent-cell

    Removing multiple cells’ data

    We will delete data from A3 to B6 range of cells:

    Sub clear_content_ex()

    ‘Clear values of range of cells

    Range(«A3:B6»).ClearContents

    End Sub

    Result:

    Excel-remove-values

    Note: If you try to recover deleted value by Ctrl+Z, or Undo from the menu – this will not work.

    Clear contents from some other sheet than active

    If you want to remove values from another sheet than the active one (or just want to specify the sheet name), you can do this as follows:

    Sub clear_content_ex()

    ‘Clear values of another sheet than active

    Worksheets(«Sheet2»).Range(«A3:B4»).ClearContents

    End Sub

    How did it work?

    • Suppose, our active sheet is “Sheet1”.
    • We specified “Sheet2” in the Worksheets object.
    • This code will clear contents of the Sheet2’s A3 to B4 cells.

    Check if the formula is also removed

    In this sheet, we used TRIM() formula in C2 to C6 cells:

    VBA-clearcontents-form

    You can see, we also applied formatting to the C column cells along with the Trim formula.

    After executing the ClearContents function, let us see what result we get:

    Sub clear_content_ex()

    ‘Clear values and formulas

    Worksheets(«Sheet3»).Range(«C2:C6»).ClearContents

    End Sub

    Result:

    clearcontents-format

    You can see:

    • Values are gone.
    • Formulas are gone.
    • The formatting is still remains.

    Return to VBA Code Examples

    In this Article

    • VBA Clear Cells / Ranges
    • VBA ClearContents
    • VBA Clear
      • VBA Clear Formatting
      • Clear Selection
      • Clear Entire Sheet

    In VBA it’s easy to clear cells or cell properties with the .Clear methods.

    VBA Clear Cells / Ranges

    Type the following into the VBA Editor.

    Range("a1").Clear

    This will display all of the Clear methods available to you:

    vba clear cells

    As you can see, You can clear:

    • Everything ( .Clear)
    • Comments ( .ClearComments)
    • Contents ( .ClearContents)
    • Formats ( .ClearFormats)
    • Hyperlinks ( .ClearHyperlinks)
    • Notes ( .ClearNotes)
    • Outline ( .ClearOutline)

    VBA ClearContents

    The most common clear method is ClearContents. ClearContents clears only the contents of cells (cell values / text). It does not clear formatting, comments, or anything else.

    Range("b2").ClearContents

    vba clearcontents

    ClearContents is the same as pressing the Delete key on your keyboard.

    You can also clear the contents of an entire range of cells:

    Range("b2:c10").ClearContents

    VBA Clear

    Clear will clear all cell properties from a cell:

    Range("b2").Clear

    vba clear

    VBA Clear Formatting

    To clear cell formatting use ClearFormats

    Range("b2").ClearFormats

    vba clear formats

    Clear Selection

    To clear the current selection:

    Selection.Clear

    Clear Entire Sheet

    To clear an entire worksheet:

    Sheets("Sheet1").Cells.Clear

    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!
    vba save as

    Learn More!

    ClearContents is a method in VBA used to delete or remove the values stored in the cells provided to it. This method makes the cell range empty. It is used with the range property to access the specified cell range. An example of this method is range(“A1:B2”). The ClearContents method will clear the contents of cells from A1 to B2.

    In Excel, adding and deleting data is a common routine task. 

    Sometimes we delete a single cell value, sometimes many cell values, and sometimes we may require to delete the entire worksheet content. This article will show you how to use the “ClearContents” method in Excel VBA. In VBA, we have many methods to do this, like “Clear,” “Delete,” and “Clear Contents.”

    Table of contents
    • Excel VBA Clear Contents
      • What are Clear Contents in Excel VBA?
      • Difference Between Clear & Delete Methods
      • Use VBA Clear Contents Method to Retain Formatting of Cells
      • Loop Through all the Worksheets and Clear Contents of Specific Range
      • Recommended Articles

    VBA Clear Contents

    What are Clear Contents in Excel VBA?

    Before we tell you about ClearContents in VBA, let me show how we can delete or clear off the data in the specific range.

     Look at the below data.

    VBA Clear contents Example 1

    Now, if we want to clear off cells A1 to C3, we need first to mention the range of cells using the VBA RANGERange 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 object.

    Code:

    Range (“A1:C3”)

    After mentioning the range of cells by using the RANGE object, we need to select the method “Clear” to clear off the mention of the cell values.

    Code:

    Range (“A1:C3”).Clear

    It will clear off the mentioned cell values.

    Code:

    Sub Clear_Example()
    
      Range("A1:C3").Clear
    
    End Sub

    VBA Clear contents Example 1-1

    VBA Clear contents Example 1-2

    Apart from the clear method, we can also use the “DELETE” method.

    Code:

    Range (“A1:C3”).Delete

    VBA Clear contents Example 1-3

    It will delete the mentioned cell values, just like our clear method.

    VBA Clear contents Example 1-4

    You can use the VBA CELLS propertyCells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells.read more with a worksheet name if you want to delete all the cell’s data.

    Worksheets(“Sheet1”).Cells.Delete
    Worksheets(“Sheet1”).Cells.Clear

    Both the above codes will delete the entire worksheet “Sheet1” data. In addition, it will delete the cell values from the first cell to the last cell of the worksheet.

    If you want to delete the present sheet cells, you can use the Active Sheet object.

    ActiveSheet.Cells.Delete or ActiveSheet.Cells.Clear

    Difference Between Clear & Delete Methods

    We know this question should have already played in your mind.

    However, there is a difference between these two methods.

    When you use the method “Delete,” it will delete the cell, and the below cell will take over the position of the deleted cell.

    For example, look at the below image.

    VBA Clear contents Example 1

    Now, we will use the delete method to delete cell A1.

    Code:

    Sub Clear_Example()
    
     Range("A1").Delete
    
    End Sub

    VBA Clear contents Example 2

    We will run this code and see what happens.

    VBA Clear contents Example 2-1

    Look what happened here. As we said, when we deleted cell A1, it got deleted, but cell A2 moved one cell up and occupies the deleted cell. So, it will lead to a data mismatch. So, be careful while using the “Delete” method.

    Now, for the same data, we will clear the method.

    Code:

    Sub Clear_Example()
    
     Range("A1").Clear
    
    End Sub

    VBA Clear contents Example 2-2

    Now, see what happens when we run this code.

    VBA Clear contents Example 2-3

    This code has just vacated cell A1 without altering other cells. Therefore, this looks like a proper method to delete only the part of the cells of the entire data range.

    Use VBA Clear Contents Method to Retain Formatting of Cells

    If you have observed the previous two methods, those two methods not only deleted or cleared off the cells provided. It also deleted the formatting of the cells we have provided.

    VBA Clear contents Example 3

    To retain the formatting of the cells, we need not use neither “Delete” nor “Clear,” but we need to use the VBA “ClearContents” method.

    When you enter the range of cells using a RANGE object, it will show all its properties and methods.

    Example 3-1

    We can access “Delete,” we can access “Clear,” and we can also access “ClearContents” methods.

    Example 3-2

    Select this method.

    Code:

    Sub Clear_Example()
    
      Range("A1:C3").ClearContents
    
    End Sub

    Example 3-3

    It will clear content from A1 to C3 cell, but we will have all the existing formatting.

    Example 3-4

    As you can see in the above picture, we have cell color in VBA, borders, and every formatting associated with those mentioned cells.

    Similarly, we can clear the contents of other sheets as well.

    Worksheets(“Sheet1”).Range(“A1:D10”).ClearContents

    It will clear the contents from cells A1 to D10 in sheet “Sheet1”.

    Similarly, we can delete the other open workbook cells as well.

    Workbooks(“Book1.xlsx”).Worksheets(“Sheet1”).Range(“A1:D10”).ClearContents

    Loop Through all the Worksheets and Clear Contents of Specific Range

    Assume you have many sheets in your workbook. You want to delete the range of cells from A1 to C15. To do this, we must use For Each Loop in VBAVBA For Each Loop helps the user to inspect and analyze the groups of objects or values individually. It even facilitates performing the specific activity for every object or value by passing a statement or group of statements in this reference.read more in all the sheets.

    The below code will do the job.

    Code:

    Sub Clear_All()
    
    Dim Ws As Worksheet
    
    For Each Ws In ActiveWorkbook.Worksheets
    Ws.Range("A1:C15").ClearContents
    Next Ws
    
    End Sub

    Example 4

    Note: You can change the range of cells as per your wish.

    If you want to clear off the entire worksheet data, then you need to use the code below.

    Code:

    Sub Clear_All()
    
     Dim Ws As Worksheet
    
     For Each Ws In ActiveWorkbook.Worksheets
       Ws.Cells.ClearContents
     Next Ws
    
    End Sub

    Example 4-1

    You can download this VBA Clear Contents Excel template here – VBA Clear Contents Template.

    Recommended Articles

    This article has been a guide to VBA Clear Contents. Here, we learn how to use the Clear, Delete, and ClearContents method in VBA to clear data in Excel and some simple to advanced examples. Below are some useful Excel articles related to VBA: –

    • New Line in VBA MsgBox
    • How to Use Timer in VBA?
    • Excel VBA Break For Loop
    • Excel VBA Do Loop
    Skip to content

    VBA ClearContents in Excel — Explained with Examples

    We can use VBA to Clear only the Content of a specific range, cells or entire worksheet. we can use ClearContents method of Range Object. Rang.ClearContents method will clear only the data in the range and the formats like border, font styles, background cell will remain same and will not be disturbed.

    VBA ClearContents Method Excel Range or Cell Object

    Excel VBA to ClearContents a Range – Syntax

    Here is the syntax to clear the contents in a range. You can clear the data in any range using VBA Range.ClearContents method.

    Range(“YourRange”).ClearContents

    Excel VBA to ClearContents in a Range – Examples

    The below macro will show you how to clear the contents in a range using VBA. In this example, we are clearing the data in range “A2 to D10” using VBA.

    Sub VBA_Clear_Contents_Range()
        Range("A2:D10").ClearContents
    End Sub
    

    Excel VBA to Clear Contents in a Range – Instructions

    Please follow the below step by step instructions to execute the above mentioned VBA macros or codes:

    1. Open an Excel Workbook from your start menu or type Excel in your run command
    2. Enter some data in any cells in range “A10 to D10” to test this macro. Also format some cell to test this macro.
    3. Press Alt+F11 to Open VBA Editor or you can go to Developer Table from Excel Ribbon and click on the Visual Basic Command to launch the VBA Editor
    4. Insert a Module from Insert Menu of VBA
    5. Copy the above code (for clearing the contents in a range using VBA) and Paste in the code window(VBA Editor)
    6. Save the file as Macro Enabled Workbook (i.e; .xlsm file format)
    7. Press ‘F5′ to run it or Keep Pressing ‘F8′ to debug the code line by line.

    Now you can observe that the data in the range “A2 to D10” is cleared. You can apply any formats and background color, and try this macro. This will clear only the data and formats will be remained same.

    If you want to clear everything including formats and data, you can use Range.Clear method, to clear the comments in a range you use the Range.ClearComments method.

    Range.ClearContents: Will clear only the content/data of the range, formats will remain same.
    Range.Clear: Will clear the data including cell formats.
    Range.ClearComments: Will clear only the comments, formats and data will remain then same.

    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 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:
    By PNRaoLast Updated: March 2, 2023

    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

    Go to Top

    Понравилась статья? Поделить с друзьями:
  • Excel classes in english
  • Excel choose if you
  • Excel choose from list
  • Excel checking if cell is empty
  • Excel check if value is in range