Excel vba удаление колонок

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

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

  • VBA Удалить столбец

VBA Удалить столбец

Копирование, вставка, вырезание, удаление, вставка — это некоторые из общих операций, используемых для выполнения в Excel. Самый простой способ сделать это, используя сочетания клавиш или встроенные функции. Но когда вы хотите выполнить операцию в один клик или автоматически, VBA является решением. Мы можем автоматизировать эти задачи, используя макросы Excel. VBA также предоставляет различные методы, аналогичные функциям Excel. Это выполняет эти задачи плавно в VBA.

Метод удаления столбцов используется для удаления одного или нескольких столбцов в Excel VBA. Свойство delete для столбцов используется вместе с индексом столбца.

Синтаксис для удаления столбца в Excel VBA

Синтаксис для удаления столбца в Excel, как показано ниже.

 Столбцы (Ссылка на столбец). удалять 
  • Где ссылка на столбец — это номер столбца, который вы хотите удалить.
  • Столбцы ((RowIndex), ColumnIndex)) здесь диапазон столбцов также принимается.

Как удалить столбец в Excel с помощью VBA?

Мы узнаем, как удалить столбец в VBA, с несколькими примерами в Excel.

Вы можете скачать этот шаблон Excel VBA Удалить столбец здесь — VBA Удалить шаблон Excel столбца

VBA Удалить столбец — Пример № 1

Из базы данных посещаемости указывается время отъезда в офис для некоторых сотрудников. Это данные, собранные за одну неделю, с понедельника по пятницу.

Мы хотим удалить столбец пятница.

Выполните следующие шаги, чтобы удалить столбец в Excel.

Шаг 1: Итак, сначала мы можем создать простую функцию как delete (), поскольку delete — это ключевое слово, которое не является предпочтительным.

Код:

 Private Sub delete () Конец Sub 

Шаг 2: Теперь давайте использовать свойство columns.

Код:

 Private Sub delete () Столбцы (6) .delete End Sub 

В столбцах () упоминается «6», поскольку указанный столбец является 6- м столбцом в таблице.

Шаг 3: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.

Если вы проверите таблицу, она будет выглядеть так, как показано ниже. Где столбец пятница был удален.

VBA Удалить столбец — Пример № 2

Другой простой способ выполнить удаление — указать ссылку на столбец в алфавитном порядке.

Выполните следующие шаги, чтобы удалить столбец в Excel с помощью VBA.

Шаг 1: Поскольку пятница — это столбец F, укажите адрес столбца, как показано ниже в коде.

Код:

 Private Sub delete1 () Столбцы ("F"). Delete End Sub 

При использовании алфавита не забудьте поставить алфавит в двойных кавычках.

Шаг 2: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.

Это удалит столбец пятница из таблицы.

VBA Удалить столбец — Пример № 3

В той же таблице, если вы хотите удалить более одного столбца, следует указать диапазон столбцов.

Выполните следующие шаги, чтобы удалить последние два столбца в Excel.

Шаг 1: Код можно изменить, как показано ниже.

Код:

 Private Sub delete2 () Столбцы ("E: F"). Delete End Sub 

Диапазон указан как «E: F», и это приведет к удалению столбца от F до G.

Шаг 2: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.

Последние два столбца удалены.

VBA Удалить столбец — Пример № 4

Посмотрим, что будет, если мы удалим средние столбцы в таблице.

Выполните следующие шаги, чтобы удалить средние столбцы в таблице.

Шаг 1: Код можно изменить, как показано ниже.

Код:

 Частные Sub столбцы delete3 () ("B: C"). Delete End Sub 

Здесь «B: C» относится к колонке понедельник и вторник.

Шаг 2: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.

После запуска кода, если вы проверите таблицу, вы можете увидеть столбец после смещения «B: C» справа налево.

VBA Удалить столбец — Пример № 5

В приведенном выше примере мы не упомянули имя рабочего листа. Если рабочая книга содержит более одного листа, то следует указать имя рабочего листа, тогда только код выполнит правильное действие.

На двух листах содержатся сведения о сотрудниках за два месяца, январь и февраль. Поскольку на одном листе имеется более одного листа, чтобы избежать ошибок, лучше указать имя листа.

Выполните следующие шаги, чтобы удалить столбец в Excel с помощью VBA.

Шаг 1: лист должен быть выбран с помощью кода.

Код:

 Частный Sub Delete4 () Рабочие листы ("Январь"). Выберите End Sub 

Шаг 2: Теперь нужно указать код для удаления столбца.

Код:

 Private Sub delete () Worksheets ("Jan"). Выберите столбцы ("B: C"). Delete End Sub 

Шаг 3: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат.

Будет выбран лист «Jan», а столбцы B, C, т.е. понедельник, вторник, будут удалены из таблицы.

Удаление нескольких столбцов с использованием объекта диапазона в VBA

Объект диапазона также используется для удаления столбца в VBA вместо удаления столбца. Если используется объект диапазона, код будет выглядеть так, как показано ниже.

 Частный Sub Удалить () Диапазон ("B: C"). Удалить End Sub 

Диапазон («B: C») представляет собой диапазон столбцов, который необходимо удалить.

Удаление одного столбца с использованием объекта диапазона

Чтобы удалить один столбец с использованием объекта диапазона, необходимо указать диапазон, как показано ниже.

 Частный диапазон Sub delete () ("B: B"). Удалить End Sub 

Диапазон («B: B») указывает на один столбец, и он будет удален.

То, что нужно запомнить

  • Столбец может быть указан с помощью номера столбца или соответствующего алфавита при удалении.
  • При удалении нескольких столбцов номера не будут приняты в качестве ссылки на столбец.
  • Вместо свойства столбцов можно использовать объект Range для удаления столбца в VBA.

Рекомендуемые статьи

Это руководство по удалению столбца VBA. Здесь мы обсудили, как удалить столбец в Excel с помощью VBA, а также с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Удаление строки с помощью VBA
  2. Excel Переместить столбцы
  3. Транспонировать диапазон в VBA
  4. Excel Удалить строку ярлык

You say you want to delete any column with the title «Percent Margin of Error» so let’s try to make this dynamic instead of naming columns directly.

Sub deleteCol()

On Error Resume Next

Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer

Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
    If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
        wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
    End If
Next i

End Sub

With this you won’t need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.

EDIT: And if your headers aren’t in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) change the «1» in Cells(1, i) to whatever row your headers are in.

EDIT 2: Changed the For section of the code to account for completely empty columns.

 

Faf

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

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

#1

19.12.2019 00:21:12

Все добрый день,

    Есть таблица (А….AA) и нужно чтобы она удалял столбцы не по названию в столбце, а по номеру столбца  и сдвигалась влево.
Я никак не могу понять, как можно вставить If then Else

Код
If (диапозон A…ААА) then
     Columns - B,C,H,J не удаляем - (как записать не удаляем - а оставляем)
Else
     Columns - которые не указаны выше удаляем

Спасибо

 

БМВ

Модератор

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

Excel 2013, 2016

не удаляем- значит ничего не делаем.

По вопросам из тем форума, личку не читаю.

 

msi2102

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

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

#3

19.12.2019 07:16:22

Можно так

Код
    For n = 12 To 1 Step -1
        If n <> 2 And n <> 3 And n <> 8 And n <> 10 Then Columns(n).Delete Shift:=xlToLeft
    Next n

или так

Код
    For n = 12 To 1 Step -1
        Select Case n
            Case 2, 3, 8, 10
            Case Else
                Columns(n).Delete Shift:=xlToLeft
        End Select
    Next n

Изменено: msi210219.12.2019 07:47:44

 

Jack Famous

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

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

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#4

19.12.2019 09:26:48

Faf, здравствуйте

Ещё несколько вариантов

Тема:

VBA. Удалить столбцы по списку

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

  • Удалить столбцы выборочно.xlsb (19.83 КБ)

Изменено: Jack Famous19.12.2019 11:55:41
(Заменена функция преобразования)

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Faf

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

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

Здорово, то что надо, всем большое спасибо!

Изменено: Faf20.11.2020 22:38:45

 

msi2102

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

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

#6

20.12.2019 06:55:25

Можно и без цикла

Код
Application.Union(Columns(2), Columns(4), Columns(6), Columns(8).Delete
 

Jack Famous

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

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

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#7

20.12.2019 09:19:30

Цитата
Faf: Я не понимаю принцип связки For In , If then

гуглите, потому что вы вообще такого странного сейчас наговорили  :D

Цитата
msi2102: Можно и без цикла

или совсем просто: Range(«B1,D1,F1»).EntireColumn.Delete

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

msi2102

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

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

#8

20.12.2019 10:06:49

Цитата
Jack Famous: Range(«B1,D1,F1»).EntireColumn.Delete

Так не хотим  :D

Цитата
Faf: нужно чтобы она удалял столбцы не по названию в столбце, а по номеру столбца

А так ещё проще  :D  :D  :D

Код
Columns(6).Delete: Columns(4).Delete: Columns(2).Delete

Изменено: msi210220.12.2019 10:10:55
(Изменил порядок удаления)

 

Jack Famous

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

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

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#9

20.12.2019 10:16:43

Цитата
msi2102: Так не хотим

ну да)) ну я для этого функцию преобразования пришил для универсальности  :D

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Faf

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

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

Удаление столбов лучше делать через циклы?

 

New

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

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

Faf, вы знаете для чего придумали циклы в программировании? Чтобы не писать тысячи одинаковых строк кода и чтобы код лучше читался. Один программист напишет программу из 1000 срок удаления 1000 столбцов, а другой программист напишет через циклы в 3 строки. Обе программы будут выполнять одно и тоже, но читаемость кода и времени написания всей программы будут лучше у циклов. Без разницы как удалять столбцы, есть разница в количестве строк кода и читаемости кода

Изменено: New21.11.2020 22:20:40

 

Faf

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

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

New,

циклы знаю, юзаю в программирование.
Если VBA это язык программирование, то ок, ясно

 

Ігор Гончаренко

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

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

#13

21.11.2020 23:56:49

судя по количеству ответов в теме — тема «удалить столбцвы по списку», не исчерпаема вглубь, как атом
(этот ответ прошу не учитывать), не претендую на раскрытие темы, я х/з как удалять столбцы «по списку» пока не определено что из себя представляет список, в котором  собраны кандидаты на удаление))

Изменено: Ігор Гончаренко22.11.2020 00:01:42

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!


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

Понравилась статья? Поделить с друзьями:
  • Excel vba удаление диапазона строк
  • Excel vba удаление всех страниц
  • Excel vba убрать форматирование
  • Excel vba убрать фильтр
  • Excel vba убрать предупреждения