Clear column in excel vba

As Gary’s Student mentioned, you would need to remove the dot before Cells to make the code work as you originally wrote it. I can’t be sure, since you only included the one line of code, but the error you got when you deleted the dots might have something to do with how you defined your variables.

I ran your line of code with the variables defined as integers and it worked:

Sub TestClearLastColumn()

    Dim LastColData As Long
        Set LastColData = Range("A1").End(xlToRight).Column

    Dim LastRowData As Long
        Set LastRowData = Range("A1").End(xlDown).Row

    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).ClearContents

End Sub

I don’t think a With statement is appropriate to the line of code you shared, but if you were to use one, the With would be at the start of the line that defines the object you are manipulating. Here is your code rewritten using an unnecessary With statement:

With Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData))
    .ClearContents
End With

With statements are designed to save you from retyping code and to make your coding easier to read. It becomes useful and appropriate if you do more than one thing with an object. For example, if you wanted to also turn the column red and add a thick black border, you might use a With statement like this:

With Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData))
    .ClearContents
    .Interior.Color = vbRed
    .BorderAround Color:=vbBlack, Weight:=xlThick
End With

Otherwise you would have to declare the range for each action or property, like this:

    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).ClearContents
    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).Interior.Color = vbRed
    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).BorderAround Color:=vbBlack, Weight:=xlThick

I hope this gives you a sense for why Gary’s Student believed the compiler might be expecting a With (even though it was inappropriate) and how and when a With can be useful in your code.

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


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


Skip to content

VBA Delete Entire Column Excel Macro Example Code

Home » VBA » VBA Delete Entire Column Excel Macro Example Code

  • VBA Delete Columns

Excel VBA code to Delete Entire Column example will help us to delete Columns in excel worksheet. We can use Delete method of Columns to delete the Entire Column. In this example we will see how to delete the entire Column in excel worksheet using VBA. Excel VBA Macro code for deleting entire Columns macro should work for all the version of Microsoft Excel 2003, Excel 2007, Excel 2010, and Excel 2013.

VBA Delete Entire Column Excel Macro Example Code

VBA code to Delete Entire Column

Here is the Example VBA syntax and Example VBA Macro code to Delete Entire Column from excel worksheets. This will help you to know how to delete entire Column from Excel workbook using VBA.

: VBA Delete Entire Column: Syntax

Following is the VBA Syntax and sample VBA macro command to Delete Entire Column from worksheet using VBA. We are using the Delete method of the Columns object of worksheet.


Columns(

[Column Number]).EntireColumn.Delete

Here Column Number is your Column number to delete. And EntireColumn.Delete method will delete the Entire Column from the Excel spreadsheet. You can also use Column Name, instead of Column Number.

Delete Entire Column using VBA: Examples

The following Excel VBA macro code is to delete entire Column from the worksheet. This VBA macro will delete the Column which we have mentioned in the code.

Sub sbVBS_To_Delete_EntireColumn ()
    Columns(1).EntireColumn.Delete
End Sub

Instructions to run the VBA Macro code to delete Entire Column

Please follow the below steps to execute the VBA code to delete entire Column.
Step 1: Open any existing Excel workbook
Step 2: Press Alt+F11 – This will open the VBA Editor
Step 3: Insert a code module from then insert menu
Step 4: Copy the above code and paste in the code module which have inserted in the above step
Step 5: enter some sample data in Column 1
Step 6: Now press F5 to execute the code

Now you can observe that the entire Column 1 is deleted from worksheet.

Explained VBA Code to Delete Entire Column:

‘Starting program and sub procedure to write VBA code to delete entire Column from sheet
Sub sbVBS_To_Delete_EntireColumn_C()

‘Specifying the Columns to delete and Deleting the Columns using EntireColumn.Delete method.
Columns(1).EntireColumn.Delete

‘Ending the sub procedure to delete entire Column
End Sub

Here Columns(1) is to tell excel to delete Column 1 of the worksheet. And Delete method will delete the entire Column form the worksheet.

VBA to Delete Entire Column in Excel :

If you want to delete the first few Columns in excel, you can repeat the delete command several times. The following example will show you how to delete the first 3 Columns in the worksheet.

Sub sbVBS_To_Delete_FirstFewColumns_in_Excel()
    Columns(1).EntireColumn.Delete
    Columns(1).EntireColumn.Delete
    Columns(1).EntireColumn.Delete
End Sub

In this example, you can see that the delete command is repeated 3 times. It will first delete the first Column, when we delete the first Column. The next Column becomes (2nd Column) the first Column. So if you delete the first Column again. The next Column (3rd Column) becomes the first Column. That means, we have deleted the first three Columns using VBA.

VBA to Delete Entire Column in Excel – VBA code Explained

Here is the explanation of the Macro to Delete first three Columns in Excel.
‘Starting the procedure to write VBA commands to delete first few (3) Columns
Sub sbVBS_To_Delete_FirstFewColumns_in_Excel_C()

‘First Column is deleting
Columns(1).EntireColumn.Delete
‘Now Second Column becomes the first Column- again we are deleting the first Column
Columns(1).EntireColumn.Delete
‘Now Third Column becomes the first Column- again delete command is deleting the first Column
Columns(1).EntireColumn.Delete
‘We have deleted the first 3 Columns, and ending the sub procedure here.
End Sub

VBA to Delete Entire Column in Excel : Using For Loop

Here is the example VBA macro to delete the first few Columns using For Loop. This will delete the first 10 records using For loop in VBA.

Sub sbVBS_To_Delete_EntireColumn_For_Loop()
Dim iCntr
    For iCntr = 1 To 10 Step 1
        Columns(1).EntireColumn.Delete
    Next
End Sub

VBA to Delete Entire Column in Excel : Using For Loop – Explanation

Here is the detailed explanation of the delete Column using for loop in VBA.
‘Starting the sub procedure to write VBA macro to delete Columns using VBA for loop
Sub sbVBS_To_Delete_EntireColumn_For_Loop_C()
‘Declaring the variable iCntr to store the for loop iterations
Dim iCntr
‘looping through the Columns using for loop, here step statement indicates the iCntr increment.
For iCntr = 1 To 10 Step 1
‘deleting the first Column
Columns(1).EntireColumn.Delete
Next
‘We have delete the first Column 10 times, it means we have deleted the first 10 Columns in excel sheet using for loop and VBA.
End Sub

VBA to Delete Entire Column in Excel: Using Do while Loop

Here is the example VBA macro to delete the first few Columns using Do while Loop. This will delete the first 10 records using For loop in VBA.

Sub sbVBS_To_Delete_EntireColumn_Do_while_Loop()
Dim iCntr
iCntr = 10 ' Last Column
    Do While iCntr >= 1
        Columns(iCntr).EntireColumn.Delete
        iCntr = iCntr - 1
    Loop
End Sub

VBA to Delete Entire Column in Excel: Using Using Do while Loop – Explanation

Here is the explanation to the above Macro to delete Columns using Do while loop.
‘Starting the VBA macro to delete the Columns using do while loop
Sub sbVBS_To_Delete_EntireColumn_Do_while_Loop()
‘Declaring the variable store the last Column number and use it as counter variable
Dim iCntr
‘assigning the last Column value to iCntr
iCntr = 10 ‘ Last Column
‘Using do while loop we are deleting the Columns from last (10th) Column
Do While iCntr >= 1
Columns(iCntr).EntireColumn.Delete
iCntr = iCntr – 1
Loop
‘ending the sub procedure here.
End Sub

Here you can observe that we are looping through the Columns from last to beginning. This will be the accurate code while deleting the Columns from worksheet. Always delete Column from last to first.

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

  • VBA code to Delete Entire Column
    • : VBA Delete Entire Column: Syntax
    • Delete Entire Column using VBA: Examples
      • Instructions to run the VBA Macro code to delete Entire Column
      • Explained VBA Code to Delete Entire Column:
      • VBA to Delete Entire Column in Excel :
      • VBA to Delete Entire Column in Excel – VBA code Explained
      • VBA to Delete Entire Column in Excel : Using For Loop
      • VBA to Delete Entire Column in Excel : Using For Loop – Explanation
      • VBA to Delete Entire Column in Excel: Using Do while Loop
      • VBA to Delete Entire Column in Excel: Using Using Do while Loop – Explanation

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:

One Comment

  1. Leo Haas
    April 17, 2015 at 11:46 PM — Reply

    Hey Rao, thought I’d drop you a message. I’m retired after 42 years in technology at a large energy company and 5 additional years at IBM. Working now with my daughter’s company trying to get information out of QuickBooks. I used to code (back in the dark ages) Cobol, CICS, Fortran. Now I’m learning VBA and am having fun doing it after being in senior management since the mid-eighties with not much fun on a daily basis! I always thought I was a great coder. I intend to be the world’s best VBA coder (it’s all about structure). Anyway, the reason your name caught my eye… one of my old friends back in the 1990’s was a guy named Uday Rao – very smart and humorous gentleman. Drop me an email sometime.

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

  • #1

I would like to clear my data in columns A,B,C in 7 of my worksheets in my workbook.

I need help creating a VBA for that?

Any help is appreciated.

Excel Facts

How can you turn a range sideways?

Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.

Smitty

Smitty

Legend

Joined
May 15, 2003
Messages
29,536


  • #2

You can record a macro grouping the 7 sheets, then select columns A, B & C on the first sheet and delete.

That would be faster than looping through sheets too.

HTH,

pgc01

MrExcel MVP

Joined
Apr 25, 2006
Messages
19,893


  • #3

An example. For the worksheets «Sheet3», «Sheet5», «Sheet7», «Sheet8», try:

Code:

Sub DelCols()
 
Worksheets("Sheet3").Columns("A:C").Clear
 
Worksheets(Array("Sheet3", "Sheet5", "Sheet7", "Sheet8")).FillAcrossSheets Worksheets("Sheet3").Columns("A:C")
 
End Sub

Similar threads

Peter_SSs

Normally in an Excel worksheet, we have two different methods to delete columns: the keyboard shortcut and the right-click and insert method. But, in VBA, we must use the “Delete” command and the entire column statement to delete any column together. If we need to delete a single column, we give a single column reference, but we give multiple column references for multiple columns.

We perform many actions in Excel like cutting, copying, pasting, adding, deleting, and inserting regularly. We can use all of these actions using VBA coding. However, one of the important concepts we need to learn in VBA is the “deleting column.” This article will show you how to use this “Delete Column” option in VBA.

Table of contents
  • Excel VBA Delete Column
    • What Does Delete Column Do in Excel VBA?
    • Examples of Excel VBA Delete Column Method
      • Example #1 – Using Delete Method
      • Example #2 – Delete Columns with Worksheet Name
      • Example #3 – Delete Blank Columns
      • Example #4 – Delete Blank Cells Columns
    • Recommended Articles

What Does Delete Column Do in Excel VBA?

As the name says, it will delete the specified column. To perform this task, we must first identify which column to delete. The selection of deleted columns differs from one scenario to another, so that we will cover some of the important and often faced scenarios in this article.

Deleting the columns is easy. First, we need to use the COLUMNS property to select the column, so VBA’s syntax of the “Delete Column” method is below.

Columns (Column Reference).Delete

So, we can construct the code like this:

Columns (2).Delete or Columns (“B”).Delete

It will delete column number 2, i.e., column B.

If we want to delete multiple columns, we cannot enter columns. Instead, we need to reference the columns by column headers, i.e., alphabets.

Columns (“A:D”).Delete

It will delete the column from A to D, i.e., the first 4 columns.

Like this, we can use the “Delete Column” method in VBA to delete particular columns. In the below section, we will see more examples to understand it better. Read on.

VBA Delete Column

Examples of Excel VBA Delete Column Method

Below are examples of deleting columns using VBA.

Example #1 – Using Delete Method

Assume you have the datasheet, something like the below.

VBA Delete Column Example 1

If we want to delete the month “Mar,” first select the column property.

Code:

Sub Delete_Example1()

  Columns(

End Sub

VBA Delete Column Example 1-1

Mention the column number or alphabet. In this case, it is either 3 or C.

Code:

Sub Delete_Example1()

  Columns(3).

End Sub

VBA Delete Column Example 1-2

Use the Delete method.

Note: You would not get the IntelliSense list to select the Delete method. Just type “Delete.”

Code:

Sub Delete_Example1()

  Columns(3).Delete

End Sub

VBA Delete Column Example 1-3

Or you can enter the column address like this.

Code:

Sub Delete_Example1()

  Columns("C").Delete

End Sub

VBA Delete Column Example 1-4

Run this code using the F5 key, or you can run it manually and see the result.

VBA Delete Column Example 1-5

Both the codes will do the same job of deleting the mentioned column.

VBA Delete Column Example 1-6

If we want to delete multiple columns, we need to mention them in the alphabet. We cannot use column numbers here.

If we want to delete columns 2 to 4, we can pass the code like the below.

Code:

Sub Delete_Example1()

  Columns("C:D").Delete

End Sub

VBA Delete Column Example 1-7

Run this code manually through the run option or press the F5 key. It will delete the columns “Feb,” “Mar,” and “Apr.”

VBA Delete Column Example 1-8

Example #2 – Delete Columns with Worksheet Name

The above is an overview of how to delete columns using VBA code. However, that is not a good practice to delete columns. Deleting the column without referring to the worksheet name is dangerous.

If you have not mentioned the worksheet name, then whichever sheet is active will delete columns of that sheet.

First, we need to select the worksheet by its name.

Code:

Sub Delete_Example2()

    Worksheets("Sales Sheet").Select

End Sub

VBA Delete Column Example 2

After selecting the sheet, we need to select the columns. We can also select the columns by using the VBA RANGE objectRange 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.

Code:

Sub Delete_Example2()

   Worksheets("Sales Sheet").Select
   Range("B:D").Delete

End Sub

VBA Delete Column Example 2-1

It will delete columns B to D of the worksheet “Sales Sheet.” For this code, it does not matter which is active. Still, it will delete the mentioned columns of that sheet only.

We can construct the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more in the single line itself.

Code:

Sub Delete_Example2()

    Worksheets("Sales Sheet").Range("B:D").Delete

End Sub

VBA Delete Column Example 2-2

It also deletes the columns “B to D” without selecting the worksheet “Sales Sheet.”

Example #3 – Delete Blank Columns

Assume you have data that has alternative blank columns like the below.

VBA DC Example 3

So, delete every alternate column. Then, we can use the below code.

Code:

Sub Delete_Example3()

    Dim k As Integer

    For k = 1 To 4
    Columns(k + 1).Delete
    Next k

End Sub

VBA DC Example 3-1

Run this code using the F5 key or manually. Then, it will delete all the alternative blank columns, and our data will look like this.

VBA Delete Column Example 3-2

Note: This works only for alternative blank columns.

Example #4 – Delete Blank Cells Columns

Now, look at this example. In certain situations, we need to delete the entire column if we find any blank cells in the data range. Consider the below data for an example.

VBA DC Example 4

All the yellow-colored cells are blank. So here, we require to delete all the blank cell columns. The below code will do that.

Code:

Sub Delete_Example4()

    Range("A1:F9").Select

    Selection.SpecialCells(xlCellTypeBlanks).Select

    Selection.EntireColumn.Delete

End Sub

VBA DC Example 4-1

Let me explain this code line by line for you.

Our data is from A1 to F9, so first, we must select that range. The below code will do that.

Range("A1:F9").Select

We need to select the blank cells in this selected range of cells. So, to select a blank cell, we need a special cell property. In that property, we have used cell type as blank.

Selection.SpecialCells(xlCellTypeBlanks).Select

Next, it will select all the blank cells, and we are deleting the entire selection column in the selection.

Selection.EntireColumn.Delete

So, our result will look like this.

VBA DC Example 4-2

Wherever it has found the blank cell, it has deleted those blank cells entirely.

You can download this Excel VBA Delete Column here – VBA Delete Column Template

Recommended Articles

This article has been a guide to VBA Delete Column. Here, we learn four methods to delete columns using Excel VBA code, practical examples, and downloadable codes. Below are some useful Excel articles related to VBA: –

  • How to Delete File in VBA?
  • VBA Integer Function
  • IsEmpty Function in VBA
  • IFERROR in VBA

Понравилась статья? Поделить с друзьями:
  • Clear all formatting excel
  • Circle the word that is different butterfly goat
  • Clear all format excel
  • Circle the word that contains a different sound write the word that is different перевод
  • Clear all cell in excel vba