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


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


193 / 9 / 1

Регистрация: 05.10.2010

Сообщений: 309

1

Очистка данных в ячейках

20.10.2011, 23:24. Показов 50551. Ответов 6


Студворк — интернет-сервис помощи студентам

Подскажите пожалуйста как можно очистить ячейки данных в VBA?



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

20.10.2011, 23:24

6

XoFfiCEr

исследователь

325 / 104 / 3

Регистрация: 18.03.2010

Сообщений: 1,079

Записей в блоге: 2

21.10.2011, 00:59

2

Цитата
Сообщение от VIG
Посмотреть сообщение

Подскажите пожалуйста как можно очистить ячейки данных в VBA?

Excel?

Visual Basic
1
2
Activesheet.Cells(1,1).Value=""                            ' одна ячейка
Activesheet.Range("A1:D5").Value=""                        ' диапазон ячеек



2



Апострофф

Заблокирован

21.10.2011, 07:36

3

Visual Basic
1
2
Activesheet.Cells(1,1).Clear                 ' полная очистка одной ячейка (Value, Format, Comments и т.д.)
Activesheet.Range("A1:D5").ClearContents          ' очистка только Value диапазона ячеек

И ещё есть несколько видов — см. ниже

Изображения

 



2



0 / 0 / 0

Регистрация: 07.08.2016

Сообщений: 47

26.12.2018, 19:20

4

А как с помощью Clear очистить лист только от значений в ячейках?т.е. к примеру чтобы закраски и форматы ячеек остались нетронутыми

Добавлено через 1 минуту
Уважаемые знатоки, подскажите как с помощью clear очистить лист только от значений ну т.е чтобы закраски и форматы ячеек остались нетронутыми??



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

26.12.2018, 19:51

5

repository, прочитайте пост выше.



1



74 / 7 / 2

Регистрация: 15.11.2018

Сообщений: 72

27.12.2018, 12:14

6

мега популярная тема. Вот оказывается что интересно форумчанам



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

27.12.2018, 13:19

7

Цитата
Сообщение от ram007
Посмотреть сообщение

мега популярная тема

— так ей уже более 7-ми лет



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

27.12.2018, 13:19

Помогаю со студенческими работами здесь

Сравнение данных в ячейках
Есть данные в первой ячейке. Во вторую добавляю часть данных из первой ячейки и надо чтобы в…

Загрузка данных, построение графика, сохранение и очистка данных
здравствуйте, нужно написать программу, в которой будет построение графика, кнопки: загрузка…

Объединение данных в ячейках Excel
добрый день!

возможно такой вопрос уже проскакивал — но как я не искал, нашел только очень…

Изменение данных в ячейках с UserForm
умоляю помогите с ума схожу уже с этой таблицей.
Проблема с копкой Изменить на второй форме, т.к…

Подсчёт данных в ячейках и строках
Необходимо подсчитать сумму чисел по строкам и столбцам, при этом в самих ячейках помимо чисел…

Форматирование данных в ячейках столбца
Здравствуйте. Подскажите пожалуйста. Есть столбец, в нем различные данные.
Например, В столбце…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

7

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

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 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.

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
 

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

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

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

 

KuklP

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

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

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

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

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

 

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

 

vikttur

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

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

Clear  
ClearContents  

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

 

Hugo

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

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

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

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

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

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

 

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

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

 

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

  всем пасибо!  

    тема клозет

 

vikttur

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

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

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

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

 

Юрий М

Модератор

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

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

#9

09.07.2012 09:52:32

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

Понравилась статья? Поделить с друзьями:
  • Очистить строки в excel команда
  • Очистить строки excel vba
  • Очистить содержимое в excel это
  • Очистить реестр от word
  • Очистить рабочий лист excel