Excel vba selection clear all

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!

As you are probably aware, Visual Basic for Application (VBA) has virtually limitless options for automating Office files, especially Excel.

When writing our code, there are several things that we can do to clean up and speed things up. In the example below, we will show how we can clear selection in VBA, whether it is a left-out selection after copying and pasting data or simply clearing a certain selected range.

Clearing Selection When Copying

For our example, we will use a random set of numbers, and we will put the numbers in column A:

Table

Description automatically generated with medium confidence

The goal now is to copy this data (located in Sheet1), to a different sheet (the sheet that we will name Sheet2). To do this, we will open the VBA by pressing ALT + F11 on our keyboard, and then we will right-click anywhere on the left side of the window that opens, and choose Insert >> Module:

Graphical user interface, application

Description automatically generated

When we do this, we will have a new window opened on the right side. There, we will insert the following code to copy and paste data from Sheet1 to Sheet2:

Sub Copy_Paste()

    Sheets(«Sheet1»).Activate

    Range(«A1:A13»).Copy

    Sheets(«Sheet2»).Activate

    Range(«A1»).PasteSpecial

End Sub

When we execute this code by pressing F5 on our keyboard while in the module, our data will be copied in Sheet2:

Table

Description automatically generated with medium confidence

When we return to Sheet1 now, we will notice that, after the code execution, our data in Sheet1 is still selected:

A screenshot of a computer

Description automatically generated with medium confidence

Luckily, there is a great option to clear this selection. This part of the code not only removes this issue but also speeds up our code, which is especially helpful if we have a large code.

All we need to do is to insert the following line at the beginning of our code:

Application.CutCopyMode = False

This instruction makes sure that selection is removed when data is copied or cut. As this line of code relates to the application (Excel) as a whole, we need to make sure to revert this when we finish executing the code. For this, we only need to add:

Application.CutCopyMode = True

At the end of the code. This is our code now:

Sub Copy_Paste()

    Application.CutCopyMode = FALSE

    Sheets(«Sheet1»).Activate

    Range(«A1:A13»).Copy

    Sheets(«Sheet2»).Activate

    Range(«A1»).PasteSpecial

    Application.CutCopyMode = TRUE

End Sub

And this is what it looks like in our module:

Graphical user interface, text, application, email

Description automatically generated

When we execute the code again, we will not have data in Sheet1 selected any longer:

A screenshot of a computer

Description automatically generated with medium confidence

Clearing Selected Range

Apart from clearing the selection when copying, we can also clear any range, by selecting it and then clearing it. The code for this is pretty easy. Let us suppose that we have random numbers in column B (range B2:B10):

Table

Description automatically generated

This will be our code to clear said data:

Sub Clearing_Data()

    Sheets(«Sheet1»).Select

    Range(«B2:B10»).Select

    Selection.Clear

End Sub

In the module, the code is as follows:

Graphical user interface, text, application, email

Description automatically generated

Once we execute this code, we will not have the data in range B2:B10.

Post Views: 1,600

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


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


Excel allows you to clear content in the worksheets selectively. So, you can clear the contents in all the cells except the ones that have formulas.

This can be useful if you use a template that has some formulas applied in it. You can delete all the cells with values and keep the formulas, so that the next time you copy paste data into it, formulas automatically calculate and you don’t have to create those again.

In this Excel tutorial, I will show you some simple methods to clear content in all the cells without deleting formulas.

So let’s get started!

Clear Cells Using Go To Special

Suppose you have a dataset as shown below where Column D has formulas in it and the rest of the cells has static values.

Below are the steps to clear the content from these cells while leaving the formulas untouched:

  1. Select the entire dataset
  2. Press the F5 key. This will open the ‘Go-To’ dialog boxGo To dialog box
  3. Click on the ‘Special’ button. This will open the ‘Go-To Special’ dialog box.Click on Special button
  4. Select the ‘Constant’ optionClick on Constant in the Go To Special dialog box
  5. Click OK.

The above steps would select only those cells that have values in it. Any cell that has a formula will not be de-selected.

Now that we have all these cells with values selected, you can hit the DELETE key to remove the values from all these cells.

In case you want to completely clear the content (including values as well as the formatting), use the below steps:

  1. With the cells (that only have the values) selected, click the Home tabClick the Home tab
  2. In the Editing group, click on the ‘Clear’ option.
  3. In the options that show up, click on the ‘Clear All’ optionClick on Clear All

The above steps would instantly remove all the content as well as the formatting from these cells.

Clear Cells Using VBA

While the above method works great, it does have a few steps/clicks that need to be done to delete values while keeping the formulas.

If you’re ok with using VBA, you can speed up this process with a simple VBA code.

Below is the VBA code that will clear the content of all the cells (within the selection) while keeping the formulas intact:

Selection.SpecialCells(xlCellTypeConstants, 23).Clear

In case you want to do the same for the entire worksheet (and not just the selection), you can use the below code:

Activesheet.cells.SpecialCells(xlCellTypeConstants, 23).Clear

Below are the steps you use this VBA code in Excel:

  1. Open the Excel workbook from where you want to clear the contents
  2. Right-click on any worksheet tab
  3. Click on the ‘View Code’ option. This will open the Visual Basic EditorClick on View code
  4. If you don’t already have the ‘Immediate window’ visible, click on the View option in the menu and then click on ‘Immediate Window’Click on VIew and then click on Immediate window
  5. Copy and paste the above code in the ‘Immediate Window’Copy paste the code in the immediate window
  6. Place the cursor at the end of the linePlace the cursor at the end of the code
  7. Hit the Enter key

The above steps would instantly clear the contents from the entire selection (expect the formulas).

In case you want to clear the contents from all the sheets (and keep the formulas intact), you can use the code below:

For Each ws In Worksheets: ws.Cells.SpecialCells(xlCellTypeConstants, 23).Clear: Next ws

The above code would go through each sheet in the workbook, clear the content from only those cells that have a constant value (while leaving the cells with formulas intact).

So these are two methods you can use to quickly clear the contents in Excel without deleting the formulas.

Hope you found this tutorial useful!

You may also like the following Excel tutorials:

  1.  How to Delete a Comment in Excel (or Delete ALL Comments)
  2. How to Unhide All Rows in Excel with VBA
  3. How to Auto Format Formulas in Excel
  4. Excel Showing Formula Instead of Result
  5. How to Remove Apostrophe in Excel
  6. How to Copy Formatting In Excel
  7. Clear Contents in Excel (Shortcut)

Содержание

  1. VBA ClearContents / Clear Cells
  2. VBA Clear Cells / Ranges
  3. VBA ClearContents
  4. VBA Clear
  5. VBA Clear Formatting
  6. Clear Selection
  7. Clear Entire Sheet
  8. VBA Coding Made Easy
  9. VBA Code Examples Add-in
  10. VBA Excel. Range.Clear и другие методы очистки ячеек
  11. Методы очистки ячеек
  12. Примеры использования
  13. 6 комментариев для “VBA Excel. Range.Clear и другие методы очистки ячеек”
  14. Setting selection to Nothing when programming Excel
  15. 17 Answers 17
  16. VBA Select and Selection
  17. The VBA Tutorials Blog
  18. Chapter 2.2 — Select and Selection
  19. Select Method
  20. Range.Offset Property
  21. Selection Property
  22. Selection.Offset Property
  23. Interior.Color Property
  24. VBA Clear Range in Excel explained with Examples
  25. VBA Reference
  26. 120+ Project Management Templates
  27. Excel VBA to Clear a Range – Syntax
  28. Excel VBA to Clear a Range – Examples
  29. Excel VBA to Clear a Range – Instructions

VBA ClearContents / Clear Cells

In this Article

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.

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

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.

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

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

VBA Clear

Clear will clear all cell properties from a cell:

VBA Clear Formatting

To clear cell formatting use ClearFormats

Clear Selection

Clear Entire Sheet

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 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 — все отлично выполняется!

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

Источник

Setting selection to Nothing when programming Excel

When I create a graph after using range.copy and range.paste it leaves the paste range selected, and then when I create a graph a few lines later, it uses the selection as the first series in the plot. I can delete the series, but is there a more elegant way to do this? I tried

but it won’t let me set selection. I also tried selection.clear, but that just cleared the last cells that were selected, and still added an extra series to the plot.

17 Answers 17

It will take you to cell A1, thereby canceling your existing selection.

thereby cancelling your selection.

Select any cell and turn off cutcopymode.

There is a way to SELECT NOTHING that solve your problem.

  1. Create a shape (one rectangle)
  2. Name it in Shapes Database >>> for example: «Ready»
  3. Refer to it MYDOC.Shapes(«Ready») and change the visibility to False

When you want that Excel SELECT NOTHING do it:

This HIDE the selection and nothing still selected in your window PLUS: The word «Ready» is shown at the Left Top in your Sheet.

You can simply use this code at the end. (Do not use False)

I do not think that this can be done. Here is some code copied with no modifications from Chip Pearson’s site: http://www.cpearson.com/excel/UnSelect.aspx.

This procedure will remove the Active Cell from the Selection.

This procedure will remove the Area containing the Active Cell from the Selection.

Tried all your suggestions, no luck , but here’s an idea that worked for me select a cell out of your selection range (say AAA1000000) and then select the A1 again

In Excel 2007, a combination using select and CutCopyMode property, it is possible to reset all the selections. It worked for my use case.

I had this issue with Excel 2013. I had «freeze panes» set, which caused the problem. The issue was resolved when I removed the frozen panes.

If you select a cell in an already selected range, it will not work. But, Selecting a range outside the original selection will clear the original selection.

* The original selection *‘ ActiveSheet.range(«A1:K10»).Select

* New Selections *‘ Activesheet.Range(«L1»).Select

* Then *‘ Activesheet.Range(«A1»).Select

You could set the Application.ScreenUpdating = False and select a cell out of view and then set the .ScreenUpdating to true. This would at least not show any selected cells in the current view.

Selection(1, 1).Select will select only the top left cell of your current selection.

If using a button to call the paste procedure,

try activating the button after the operation. this successfully clears the selection

  • having to mess around with hidden things
  • selecting another cell (which is exactly the opposite of what was asked)
  • affecting the clipboard mode
  • having the hacky method of pressing escape which doesn’t always work

None of the many answers with Application.CutCopyMode or .Select worked for me.

But I did find a solution not posted here, which worked fantastically for me!

If you are really wanting ‘nothing selected`, you can use VBA to protect the sheet at the end of your code execution, which will cause nothing to be selected. You can either add this to a macro or put it into your VBA directly.

As soon as the sheet is unprotected, the cursor will activate a cell.

Hope this helps someone with the same problem!

Источник

VBA Select and Selection

The VBA Tutorials Blog

Chapter 2.2 — Select and Selection

Excel VBA Tutorials

Select Method

The Select Method presented here is an important method of the Range Object.

Result:

The Range.Select Method selects the cells in your range.

Range.Offset Property

The Offset Property adjusts your position based on the initial Range you define.

Result:

The Offset Property accepts two arguments: a row and a column. In the example above, the range is offset by 1 row and 2 columns before being selected.

Selection Property

The Selection Property refers to the currently selected range or item and can be used to manipulate values. As a general rule of thumb, most things you can perform with the Range Object, you can also perform with Selection. Keep in mind that selecting cells individually in your VBA macros will slow your code down. I recommend using Application.ScreenUpdating=False if you’re selecting cells.

Selection.Offset Property

Result:

Offsetting the currently selected cell by 1 row is quite useful inside long VBA loops. If you’re a loyal follower of my VBA Tutorials Blog, I’m sure you’ve seen me do this. The Selection property is rarely needed, but I’ll use it on occasion inside large loops since the Integer Data Type is limited to integers less than 32,767.

Interior.Color Property

Result:

The Color Property, a property of the Interior Object, is used to change the cell color. Remember, you can use Selection.Clear to clear the formatting.

In this lesson, you learned about the Select Method of the Range Object and about the Selection Property. You learned how to offset your current selection, which is useful inside long VBA loops, and you learned that Selection shares many Properties and Methods with the Range Object.

If you really want to learn VBA, grab a copy of our Ultimate VBA Training Bundle before reading our next tutorial. We specifically created these cheat sheets to help you get the most out of our upcoming lessons. Together, the set has over 200 practical tips covering the 125 most important topics in Excel VBA. We also stuffed it with 140 helpful macro examples.

Источник

VBA Clear Range in Excel explained with Examples

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:

50+ Excel Templates

50+ PowerPoint Templates

25+ Word 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
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 Clear Range in Excel will Clear a specific range or entire worksheet using Clear method of Range Object. ‘Rang.Clear’ method will clear the range including the formats like border, font styles, background cell and set to default.

Excel VBA to Clear a Range – Syntax

Here is the syntax to clear a range. You can clear the data in any range including formats using VBA ‘Range.Clear’ method.

Excel VBA to Clear a Range – Examples

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

Excel VBA to Clear 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.
  3. Press Alt+F11 to Open VBA Editor or you can goto 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 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 range “A2 to D10” is clear. You can apply any formats and background color, and try this macro. This will clear everything and set to the default.

If you want to clear only the data you can use Range.ClearContents method, to clear the comments in a range you use the Range.ClearComments method.

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

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.

Источник

Понравилась статья? Поделить с друзьями:
  • Excel vba select selected row
  • Excel vba select from table
  • Excel vba select from listbox to
  • Excel vba select cell from range
  • Excel vba select case in select case