Vba excel как удалить колонку

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

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

You can use the following methods to delete columns in Excel using VBA:

Method 1: Delete One Column

Sub DeleteColumns()
Columns("C").Delete
End Sub

This particular example will delete column C from the current workbook.

Method 2: Delete All Columns in Range

Sub DeleteColumns()
Columns("B:D").Delete
End Sub

This particular example will delete all columns in the range B through D in the current workbook.

Method 3: Delete Several Specific Columns

Sub DeleteColumns()
Range("B:B, D:D").Delete
End Sub

This particular example will delete columns B and D in the current workbook.

The following examples show how to use each of these methods in practice with the following dataset in Excel:

Example 1: Delete One Column in VBA

We can create the following macro to delete only column C from our dataset:

Sub DeleteColumns()
Columns("C").Delete
End Sub

When we run this macro, we receive the following output:

Notice that only column C (the “Assists” column) has been deleted from the dataset.

Example 2: Delete All Columns in Range

We can create the following macro to delete all columns in the range from B to D:

Sub DeleteColumns()
Columns("B:D").Delete
End Sub

When we run this macro, we receive the following output:

Notice that each column in the range from B to D (the “Points”, “Assists”, and “Rebounds” columns) have been deleted from the dataset.

Example 3: Delete Several Specific Columns

We can create the following macro to delete columns B and D from the dataset:

Sub DeleteColumns()
Range("B:B, D:D").Delete
End Sub

When we run this macro, we receive the following output:

Notice that columns B and D (the “Points” and “Rebounds” columns) have been deleted from the dataset.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

VBA: How to Count Number of Rows in Range
VBA: How to Count Number of Used Columns
VBA: How to Find Last Used Column

4377 / 661 / 36

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

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

1

06.04.2010, 21:14. Показов 57785. Ответов 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



11482 / 3773 / 677

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

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

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

Сообщений: 247

21.05.2021, 01:46

17

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



0



 

BretHard120

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

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

#1

02.09.2013 10:21:56

Привет, всем  :)

Как удалить несколько несмежный столбцов с помощью VBA ? Столбы A, D, E, содержащие «100» (пример во вложенном файле).

Набираю:

Код
Dim WE As Excel.Workbook
Dim WS As Excel.Worksheet

Public Sub Stolbci()

Set WE = ActiveWorkbook
Set WS = Application.Workbooks("Столбцы.xlsm").Worksheets(1)

WS.Columns("A", "D:E").Delete

End Sub
 

В строке WS.Columns(«A», «D:E»).Delete выскакивает ошибка. Как правильно?

Прикрепленные файлы

  • Столбцы.xlsm (13.06 КБ)

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

#2

02.09.2013 10:26:26

Если прочитать справку по Columns, то станет ясно, что в качестве параметра можно указывать только цифры. Никаких букв. С буквами работает только Range:

Код
WS.Range("A1", "D1:E1").Entirecolumn.Delete

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

BretHard120

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

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

#3

02.09.2013 10:44:21

Цитата
Если прочитать справку по Columns, то станет ясно, что в качестве параметра можно указывать только цифры.

Почему тогда если оставить, например,

Цитата
WS.Columns(«A»).Delete

то столбец А удалится?

После ввода

Цитата
WS.Range(«A1», «D1:E1»).Entirecolumn.Delete

удаляются все столбцы, кроме «F», а можно ли оставить еще B,C?

 

anvg

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

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

Excel 2016, 365

#4

02.09.2013 11:01:55

Что то вы перемудрили с форматом указания диапазонов. Так оставляети В и С.

Код
WS.Range("A1,D1:E1").EntireColumn.Delete
 

BretHard120

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

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

#5

02.09.2013 11:09:29

Цитата
Что то вы перемудрили с форматом указания диапазонов. Так оставляети В и С.

Видимо, B и C удалились из-за лишней кавычки.

Спасибо за ответы, помогло.

Понравилась статья? Поделить с друзьями:
  • Vba excel как удалить кнопку с листа
  • Vba excel как удалить картинку с листа
  • Vba excel как удалить выделенную строку
  • Vba excel как удалить userform
  • Vba excel как убрать пробелы в строке