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


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


Return to VBA Code Examples

This tutorial will demonstrate how to clear the formatting of a cell or entire range of cells.

You can clear cell formatting by using the ClearFormats method of the Range Object.

Note: Instead, if you’d like to clear everything about the cell use .Clear instead.

Clear Formats From a Range of Cells

This will clear Cell Formatting for Range A1:C1.

Sub ClearFormats()
      Range("A1:C1").ClearFormats
End Sub

If you’d like to clear the formatting of an entire worksheet, use the Cells Object instead:

Sub ClearSheetFormats()
      Cells.ClearFormats
End Sub

If you are working with an extremely large range in a large Workbook, Excel could potentially freeze. you could also loop through each cell to prevent Excel from freezing.

Loop through Cells and Clear Formats

The following example will eliminate the formatting for each cell in a range using a loop:

Public Sub RemoveFormatting()
Dim c As Range

For Each c In Range("A:A")
     c.ClearFormats
Next c

End Sub

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!

alt text

Learn More!

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Cells to clear: This VBA code clears all of the formats in range («A1:B2»), therefore if you are using the exact VBA code the cells in which you want to clear the formatting need to be captured in this range.
Worksheet Name: Have a worksheet named Analysis.

ADJUSTABLE PARAMETERS
Cells to clear: Select the range of cells that you want to clear by changing the range («A1:B2») in the VBA code to any range in the worksheet that contains the cells in which you want to remove the formatting.
Worksheet Selection: Select the worksheet that contains the cells in which you want to remove the formatting by changing the Analysis worksheet name, in the VBA code, to any worksheet in the workbook.

Skip to content

VBA ClearFormats in Excel Explained with Examples

We can use VBA to Clear only the Formats of a specific range, cells or entire worksheet. we can use ClearFormats method of Range Object. Rang.ClearFormats method will clear only the formats of the cells or range. And the data and comments will not be deleted.

VBA ClearFormats Method Excel Range Object

Excel VBA to ClearFormats a Range – Syntax

Here is the syntax to clear the formats of a range. You can clear the formats in any range using VBA Range.ClearFormats method.

Range(“YourRange”).ClearFormats

Excel VBA to ClearFormats in a Range – Examples

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

Sub VBA_Clear_Formats_Range()
    Range("A2:D10").ClearFormats 
End Sub

Excel VBA to Clear Formats 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 formats 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 formats in the range “A2 to D10” are cleared. You can apply any formats and background color, and try this macro. This will clear only the formats and the data, comments will be remained same.

Range.ClearFormats:Will clear only the formats of a range, remaining elements untouched.
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
  • Excel VBA to ClearFormats a Range – Syntax
  • Excel VBA to ClearFormats in a Range – Examples
  • Excel VBA to Clear Formats in a Range – Instructions

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

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 VBA Tutorial about how to clear cell with macrosIn this VBA Tutorial, you learn how to clear cells (including clearing cells totally, their format but not their contents, their contents but not their format, and other similar combinations) with macros.

This VBA Tutorial is accompanied by Excel workbooks containing the macros I use in the examples below. You can get immediate access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.

Use the following Table of Contents to navigate to the section you’re interested in.

Related VBA and Macro Tutorials

The following VBA and Macro Tutorials may help you better understand and implement the contents below:

  • General VBA constructs and structures:
    • Learn about important VBA constructs here.
    • Learn how to work with the Visual Basic Editor here.
    • Learn how to work with Excel Sub procedures here.
    • Learn about the Excel Object Model, and how to create object references, here.
    • Learn about the Range object, and how to refer to cells, here.
    • Learn how to work with properties here.
    • Learn how to work with methods here.
    • Learn how to declare and work with variables here.
    • Learn about data types here.
    • Learn how to work with loops here.
  • Practical VBA applications and macro examples:
    • Learn how to work with worksheets using VBA here.
    • Learn how to check if a cell is empty here.
    • Learn how to delete rows here.
    • Learn how to delete blank or empty rows here.

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

VBA Code to Clear Cell

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

Cells.Clear

Process Followed by VBA to Clear Cell

Identify cells to clear > clear cells entirely

VBA Statement Explanation

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

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

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

Macro Example to Clear Cell

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

Sub clearCell()

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

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

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

    'clear cells (including formatting)
    myRange.Clear

End Sub

Effects of Executing Macro Example to Clear Cell

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

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

    Cells with data, fill color and bold formatting

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

    Cells with cleared data and formatting

#2: Clear Cell Contents and Keep Formatting

VBA Code to Clear Cell Contents and Keep Formatting

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

Cells.ClearContents

Process Followed by VBA to Clear Cell Contents and Keep Formatting

Identify cells to clear > clear cell contents but keep formatting

VBA Statement Explanation

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

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

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

Macro Example to Clear Cell Contents and Keep Formatting

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

Sub clearCellContentsKeepFormatting()

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

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

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

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

End Sub

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

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

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

    Cells with data, interior fill and bold formatting

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

    Cells with interior fill and bold formatting

#3: Clear Cell Formatting

VBA Code to Clear Cell Formatting

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

Cells.ClearFormats

Process Followed by VBA to Clear Cell Formatting

Identify cells to clear > clear cell formatting

VBA Statement Explanation

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

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

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

Macro Example to Clear Cell Formatting

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

Sub clearCellFormatting()

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

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

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

    'clear cell formatting
    myRange.ClearFormats

End Sub

Effects of Executing Macro Example to Clear Cell Formatting

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

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

    Cells with data, interior fill and bold formatting

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

    Cells with data but cleared formatting

#4: Clear Cell Color

VBA Code to Clear Cell Color

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

Cells.Interior.Color = xlColorIndexNone

Process Followed by VBA to Clear Cell Color

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

VBA Statement Explanation

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

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

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

Macro Example to Clear Cell Color

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

Sub clearCellColor()

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

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

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

    'clear cell color
    myRange.Interior.Color = xlColorIndexNone

End Sub

Effects of Executing Macro Example to Clear Cell Color

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

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

    Cells with data, interior fill and bold formatting

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

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

#5: Clear Cells with Zero

VBA Code to Clear Cells with Zero

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

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

Process Followed by VBA to Clear Cells with Zero

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

VBA Statement Explanation

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

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

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

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

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

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

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

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

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

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

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

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

Macro Example to Clear Cells with Zero

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

Sub clearCellsWithZero()

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

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

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

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

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

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

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

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

    Next iCell

End Sub

Effects of Executing Macro Example to Clear Cells with Zero

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

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

    Cells with data and zero, fill color and bold formatting

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

    Some cells with data, fill color and bold formatting

References to VBA Constructs Used in this VBA Tutorial

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

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

Понравилась статья? Поделить с друзьями:
  • Очистить формат таблицы word
  • Очистить формат горячая клавиша excel
  • Очистить формат word 2003
  • Очистить фильтр excel vba
  • Очистить умную таблицу excel vba