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


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


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!

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

Очистить весь лист с кодом VBA в Excel
Очистить указанный диапазон с кодом VBA в Excel


Очистить весь лист с кодом VBA в Excel

Приведенные ниже коды VBA помогут вам очистить весь лист с форматированием ячеек или без него.

1. нажмите другой + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окна, нажмите Вставить > Модули, а затем скопируйте ниже код VBA в модуль.

Если вы просто хотите очистить содержимое ячейки, но сохранить форматирование, попробуйте этот код.

Код VBA: очистить весь лист без форматирования ячеек

Sub sbClearEntireSheetOnlyData()
Sheets("Sheet4").Cells.ClearContents
End Sub

Если вы хотите очистить и содержимое, и форматирование ячеек, этот код может вам помочь.

Код VBA: очистить весь лист с форматированием ячеек

Sub sbClearEntireSheet()
Sheets("Sheet4").Cells.Clear
End Sub

Внимание: В коде Sheet4 — это имя рабочего листа, с которого вы очистите содержимое. Пожалуйста, измените его по своему усмотрению.

3. нажмите F5 или нажмите кнопку «Выполнить», чтобы запустить код.

Затем указанный рабочий лист с форматированием ячеек или без него немедленно очищается.


Очистить указанный диапазон с кодом VBA в Excel

Для очистки только указанного диапазона на листе вы можете попробовать следующий код VBA.

1. Откройте рабочий лист, из которого вы очистите указанный диапазон, затем нажмите другой + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окна, нажмите Вставить > Модули, а затем скопируйте ниже код VBA в модуль.

Очистить диапазон, но сохранить форматирование, попробуйте этот код.

Код VBA: очистить указанный диапазон без форматирования ячеек

Sub sbClearCellsOnlyData()
Range("A1:C10").ClearContents
End Sub

Очистить диапазон с форматированием ячеек, используйте этот код:

Код VBA: очистить указанный диапазон с форматированием ячеек

Sub sbClearCells()
Range("A1:C10").Clear
End Sub

Внимание: A1: C10 — это диапазон, который вы очистите на листе.

3. нажмите F5 ключ или щелкните Run кнопку, чтобы очистить диапазон.


Статьи по теме:

  • Как очистить ограниченные значения в ячейках в Excel?
  • Как очистить кеш фильтра (старые элементы) из сводной таблицы в Excel?

Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Комментарии (0)


Оценок пока нет. Оцените первым!

Иногда есть необходимость перед какими-то действиями сначала очистить лист Excel от всех данных, которые на нем есть, чтобы заполнить его новыми данными. Я предлагаю 3 варианта как можно очистить лист.

Способ 1

Очистка всех ячеек на листе

' Очистка всех ячеек от данных, а так же оформления ячеек (шрифт, фон и т.п.)
Sheets("Лист1").Cells.Clear

Либо, если нужно очистить только данные на листе Excel, не затрагивая формат ячеек, можно сделать так:

' Очистка всех ячеек только от данных
Sheets("Лист1").Cells.ClearContents

Способ 2

Чтобы очистить все данные и при этом определение последней строки SpecialCells(xlCellTypeLastCell) работало правильно, можно воспользоваться таким вариантом:

Sheets("Лист1").Cells.Delete Shift:=xlUp
ThisWorkbook.Saved = True

Способ 3

Если лист содержит очень преочень много данных, тогда чтобы очистить лист Excel самым быстрым способом будет удалить его и создать заново.

' Отключаем предупреждение об удалении данных на листе
Application.DisplayAlerts = False
' Удаляем лист
Sheets("Лист1").Delete
' Включаем предупреждения обратно
Application.DisplayAlerts = True
' Добавляем лист
Set Sheet = Sheets.Add
' Переименовываем как он назывался перед удалением
Sheet.Name = "Лист1"

Предложенных 3 вариантов удаления всех данных на листе Excel я думаю будет достаточно для решения повседневных задач на VBA.

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

Понравилась статья? Поделить с друзьями:
  • Очистка всех формул excel
  • Очистка временных файлов excel
  • Очистка вне диапазона excel
  • Очистка word от мусора
  • Очистка html кода word