Удалить всю колонку vba excel

In this Article

  • Delete Entire Row or Column
    • Delete Multiple Rows or Columns
  • Delete Blank / Empty Rows
    • Delete Row if Cell is Blank
  • Delete Row Based on Cell Value
  • More Delete Row and Column Examples
    • Delete Duplicate Rows
    • Delete Table Rows
    • Delete Filtered Rows
    • Delete Rows in Range
    • Delete Selected Rows
    • Delete Last Row
    • Delete Columns by Number

This tutorial will demonstrate different ways to delete rows and columns in Excel using VBA.

Delete Entire Row or Column

To delete an entire row in VBA use this line of code:

Rows(1).Delete

Notice we use the Delete method to delete a row.

Instead of referencing the Rows Object, you can reference rows based on their Range Object with EntireRow:

Range("a1").EntireRow.Delete

Similarly to delete an entire column, use these lines of code:

Columns(1).Delete
Range("a1").EntireColumn.Delete

Delete Multiple Rows or Columns

Using the same logic, you can also delete multiple rows at once:

Rows("1:3").Delete

or columns:

Columns("A:C").Delete

Notice here we reference the specific row and column numbers / letters surrounded by quotations.

Of course, you can also reference the EntireRow of a range:

Range("a1:a10").EntireRow.Delete

Note: The examples below only demonstrate deleting rows, however as you can see above, the syntax is virtually identically to delete columns.

Delete Blank / Empty Rows

This example will delete a row if the entire row is blank:

Sub DeleteRows_EntireRowBlank()

Dim cell As Range

For Each cell In Range("b2:b20")
    If Application.WorksheetFunction.CountA(cell.EntireRow) = 0 Then
        cell.EntireRow.Delete
    End If
Next cell

End Sub

It makes use of the Excel worksheet function: COUNTA.

Delete Row if Cell is Blank

This will delete a row if specific column in that row is blank (in this case column B):

Range("b3:b20").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

Delete Row Based on Cell Value

This will loop through a range, and delete rows if a certain cell value in that row says “delete”.

Sub DeleteRowswithSpecificValue()

Dim cell As Range

For Each cell In Range("b2:b20")
    If cell.Value = "delete" Then
        cell.EntireRow.Delete
    End If
Next cell

End Sub

More Delete Row and Column Examples

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!

automacro

Learn More

Delete Duplicate Rows

This code will delete all duplicate rows in a range:

Range("b2:c100").RemoveDuplicates Columns:=2

Notice we set Columns:=2. This tells VBA to check both the first two columns of data when considering if rows are duplicates. A duplicate is only found when both columns have duplicate values.

If we had set this to 1, only the first row would’ve been checked for duplicate values.

Delete Table Rows

This code will delete the second row in a Table by referencing ListObjects.

ThisWorkbook.Sheets("Sheet1").ListObjects("list1").ListRows(2).Delete

Delete Filtered Rows

To delete only rows that are visible after filtering:

Range("b3:b20").SpecialCells(xlCellTypeVisible).EntireRow.Delete

VBA Programming | Code Generator does work for you!

Delete Rows in Range

This code will delete all rows in range:

Range("a1:a10").EntireRow.Delete

Delete Selected Rows

This code will delete all selected rows:

Selection.EntireRow.Delete

Delete Last Row

This will delete the last used row in column B:

Cells(Rows.Count, 2).End(xlUp).EntireRow.Delete

By changing 2 to 1, you can delete the last used row in column A, etc.:

Cells(Rows.Count, 1).End(xlUp).EntireRow.Delete

Delete Columns by Number

To delete a column by it’s number, use a code like this:

Columns (2).Delete

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

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 Delete Column (wallstreetmojo.com)

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

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


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


This code is an attempt to delete columns that contain Header rows that match the “Text” in the Array (list).

The code successfully deletes the column based on the 1st array value «Header Text 1».

The problem occurs during the 2nd pass of the loop on A.EntireColumn.Delete. When I print the vItem, it displays the expected “Header Text 2” value, which is the correct item in the array.

VBA Error – Runtime error ‘91’

Object variable or With block variable not set

Sub ArrayLoop()
Dim ColumnsToRemove As Variant
Dim vItem As Variant
Dim A As Range

ColumnsToRemove = Array("Header Text 1", "Header Text 2", "Header Text 3")

For Each vItem In ColumnsToRemove

    Set A = Rows(1).Find(What:=(ColumnsToRemove), LookIn:=xlValues, lookat:=xlPart)
    Debug.Print vItem
    A.EntireColumn.Delete

Next
End Sub

0m3r's user avatar

0m3r

12.2k15 gold badges33 silver badges70 bronze badges

asked Feb 29, 2016 at 20:33

FNH4410's user avatar

1

You need to look for vItem, and you need to add a check to see if it was found before trying to delete the column it’s in.

Sub ArrayLoop()
Dim ColumnsToRemove As Variant
Dim vItem As Variant
Dim A As Range

ColumnsToRemove = Array("Header Text 1", "Header Text 2", "Header Text 3")

For Each vItem In ColumnsToRemove

    Set A = Rows(1).Find(What:=vItem, LookIn:=xlValues, _
                          lookat:=xlPart)

    Debug.Print vItem, Not A Is Nothing

    If Not A Is Nothing Then A.EntireColumn.Delete

Next
End Sub

answered Feb 29, 2016 at 20:59

Tim Williams's user avatar

Tim WilliamsTim Williams

150k8 gold badges96 silver badges124 bronze badges

3

A way to loop through an index is to use ubound and lbound:

Sub ArrayLoop()
Dim ColumnsToRemove As Variant
Dim vItem As Variant
Dim A As Range
Dim i As Long

ColumnsToRemove = Array("Header Text 1", "Header Text 2", "Header Text 3")


For i = LBound(ColumnsToRemove) To UBound(ColumnsToRemove)
    Set A = Rows(1).Find(what:=ColumnsToRemove(i), LookIn:=xlValues, lookat:=xlPart)
    Debug.Print ColumnsToRemove(i) ' not sure what `vItem` was intended to be
If A Is Nothing Then
    Debug.Print "Nothing found"
ElseIf Not A Is Nothing Then
    A.EntireColumn.Delete
End If
Next i

End Sub

answered Feb 29, 2016 at 21:01

BruceWayne's user avatar

BruceWayneBruceWayne

22.8k15 gold badges64 silver badges109 bronze badges

1

Sub ArraybLoop()
Dim ColumnsToRemove() As Variant
Dim vItem As Variant
Dim A As Range
Dim i As Long
Dim Sht As Worksheet

Set Sht = ActiveWorkbook.Sheets("Sheet1")

ColumnsToRemove = Array("Header Text 1", "Header Text 2", "Header Text 3")


    For i = LBound(ColumnsToRemove) To UBound(ColumnsToRemove) Step 1
        vItem = Application.Match(ColumnsToRemove(i), Sht.Rows(1), 0)

        Debug.Print vItem

        If IsNumeric(vItem) Then Sht.Columns(vItem).Delete
    Next i

End Sub

Upper and Lower Bounds

Understanding Arrays

answered Feb 29, 2016 at 21:00

0m3r's user avatar

0m3r0m3r

12.2k15 gold badges33 silver badges70 bronze badges

1

4377 / 661 / 36

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

Сообщений: 2,134

1

06.04.2010, 21:14. Показов 57817. Ответов 16


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

Столбец проходит через диапазон обьединенных ячеек (например Сolumns(h) через ячейку, обьеденившую ячейки G10, H10, i10) Отменять обьединение не желательно. Что только не пробую — глухо.



0



paladin

286 / 186 / 7

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

Сообщений: 589

07.04.2010, 07:47

2

Если удалять столбец, в котором находится первая ячейка из объединенных, то данные из нее теряются . По идее можно все такие ячейки разъединять, копировать значение в следующую за ней, снова объединять как надо (как было, за исключением удаляемого) и проводить удаление лишнего столбца.
Также можно просто скрыть столбец. Тогда дополнительно что-то делать не потребуется.



0



4377 / 661 / 36

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

Сообщений: 2,134

07.04.2010, 14:54

 [ТС]

3

To Yurij. Спасибо за ответ, но ситуация не стандартная, таблица большая, в ней много обьединенных ячеек разной длинны, причем размещены на листе асиметрически. Сделать можно, но очень долго. Может есть какое-нибудь решение попроще?



0



11483 / 3774 / 677

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

Сообщений: 11,148

08.04.2010, 00:38

4

Старайся не применять объединение ячеек. С ним всегда столько геморроя



0



496 / 130 / 19

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

Сообщений: 224

08.04.2010, 14:24

5

Для удаления столбца нужно применить метод Delete, непосредственно к самому столбцу, не выделяя его перед этим
Для сравнения:

Columns(h).Delete ‘удаляет только указанный столбец

Columns(h).Select
Selection.Delete ‘удаляет все столбцы, участвующие в объединении



1



4377 / 661 / 36

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

Сообщений: 2,134

11.04.2010, 11:14

 [ТС]

6

Цитата
Сообщение от petr-sev
Посмотреть сообщение

Для удаления столбца нужно применить метод Delete, непосредственно к самому столбцу, не выделяя его перед этим
Для сравнения:

Columns(h).Delete ‘удаляет только указанный столбец

Columns(h).Select
Selection.Delete ‘удаляет все столбцы, участвующие в объединении

Спасибо, работает. Действительно, для контроля я выделял столбец, что в окончательном варианте кода планировалось удалить. Теперь все на месте. Еще раз спасибо.



1



24 / 8 / 17

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

Сообщений: 2,099

01.03.2016, 02:48

7

у меня есть 6 столбцов и 16 строк как в цикле FOR
удалить стоблбцы и строки в диапазоне с(задаеться textbox1.value=3) по
‘к-во всего столбцов в бд
cellx = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell) .Column
‘к-во всего строк в бд
rowx = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell) .row



0



Казанский

15136 / 6410 / 1730

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

Сообщений: 9,999

01.03.2016, 03:03

8

scherbakovss201, а зачем в цикле?

Visual Basic
1
2
range(columns(3),columns(cellx)).delete 'столбцы
range(rows(3),rows(rowx)).delete 'строки



0



24 / 8 / 17

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

Сообщений: 2,099

01.03.2016, 04:09

9

вы не знаете какое пользователь в textbox1 ведет значение.Пример для трех хорош.



0



Казанский

15136 / 6410 / 1730

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

Сообщений: 9,999

01.03.2016, 09:02

10

scherbakovss201, а вместо «3» подставить значение текстбокса — не судьба?

Visual Basic
1
2
3
n=val(textbox1.value)
range(columns(n),columns(cellx)).delete 'столбцы
range(rows(n),rows(rowx)).delete 'строки



0



inquisitor

24 / 8 / 17

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

Сообщений: 2,099

01.03.2016, 17:19

11

О так можно удалять без цикла.Круто.А можно ли загрузать(открыть/импортировать) бд екселе на vba
скажем не всю,а только к-во строк/стролбцов указанных в textbox1.value?

PureBasic
1
2
3
4
5
Private Sub C()
    Workbooks.OpenDatabase Filename:= _
        "C:UsersuserDownloadslabзадачиlab1Database31.accdb", CommandText:=Array( _
        "копия ""сотрудники"""), CommandType:=xlCmdTable, ImportDataAs:=xlTable
End Sub



0



1 / 1 / 0

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

Сообщений: 3

17.01.2019, 16:45

12

Почему у меня компилятор ругается

Sheets(«ДГМ»).Range(Columns(8), Columns(20)).Delete

Добавлено через 19 минут
ActiveSheet.Range(Cells(1, 7), Cells(LastRowSheetsFasad, LastCol)).Select
итак тоже не работает

Добавлено через 33 минуты
Решил проблему вот таким простым способом
For j = 8 To LastCol
Sheets(«ДГМ»).Columns(8).Delete
Next j



0



pashulka

4131 / 2235 / 940

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

Сообщений: 4,624

17.01.2019, 19:12

13

DANGER1979, Если в момент удаления лист с именем «ДГМ» не активен, то :

Visual Basic
1
Sheets("ДГМ").Range(Sheets("ДГМ").Columns(8), Sheets("ДГМ").Columns(20)).Delete

Добавлено через 3 минуты
Хотя в Вашем случае достаточно и :

Visual Basic
1
Sheets("ДГМ").Range("H:T").Delete
Visual Basic
1
Sheets("ДГМ").Columns("H:T").Delete
Visual Basic
1
Sheets("ДГМ").Columns(8).Resize(, 13).Delete



1



DANGER1979

1 / 1 / 0

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

Сообщений: 3

24.01.2019, 12:38

14

PureBasic
1
2
Sheets("ДГМ").Range(Sheets("ДГМ").Columns(8), Sheets("ДГМ").Columns(LastCol)).Delete 
Sheets("ДГМ").Columns(8).Resize(, LastCol).Delete

оба эти варианта работает плохо,
т.к. подсчёт суммы (=RC[-1]*СУММ(RC[1]:RC[21])*R8C6) в 6 столбце по всем столбцам теряет привязку к 7 столбцу и последнему пустому столбцу

Мой вариант

PureBasic
1
2
3
    For j = 8 To LastCol
        Sheets("ДГМ").Columns(8).Delete
    Next j

т.е. мы удаляем с 8 по последний столбец с данными
работает так как надо



0



pashulka

4131 / 2235 / 940

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

Сообщений: 4,624

24.01.2019, 16:34

15

DANGER1979,

1) Вопрос был «почему у меня компилятор ругается» и не более

2) Два представленных варианта различаются, ибо правильно будет так :

Visual Basic
1
Sheets("ДГМ").Columns(8).Resize(, LastCol - 7).Delete

3) Если Вы утверждаете, что результаты, после удаления одних и тех же столбцов, различаются, приложите файл (.xls/.xlsm) оставив там только нужные и обезличенные данные и макросы.



0



0 / 0 / 0

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

Сообщений: 13

19.05.2021, 16:10

16

Ребята подскажите как удалить 1 нужный мне столбец к примеру «D» со сдвигом влево ?



0



Ученик

87 / 69 / 16

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

Сообщений: 248

21.05.2021, 01:46

17

lovator, доброго времени суток. Включите макрорекодер для того чтоб записать макрос. Выделите нужный вам столбец и удалите его со сдвигом влево. Остановите запись макроса в макрорекодере, ALT+F11 увидеть свой макрос для удаление столбца. Удачи вам.



0



Понравилась статья? Поделить с друзьями:
  • Удалить все что после символа word
  • Удалить дело в excel
  • Удалить все что после запятой в excel
  • Удалить двойной пробел в word
  • Удалить все фотографии word