How to Delete Columns in Excel VBA
In Excel VBA, you can delete columns using the Delete
method of the Range
object.
Syntax:
Worksheets("Sheet1").Columns(1).Delete
The above syntax will delete the entire first column in the worksheet named “Sheet1”.
Example:
Suppose we have the following data in our Excel worksheet:
Column A | Column B | Column C |
---|---|---|
Data A1 | Data B1 | Data C1 |
Data A2 | Data B2 | Data C2 |
Data A3 | Data B3 | Data C3 |
To delete the second column, we can use the following VBA code:
Sub DeleteColumn() Worksheets("Sheet1").Columns(2).Delete End Sub
Running this code will delete the second column, resulting in the updated data:
Column A | Column C |
---|---|
Data A1 | Data C1 |
Data A2 | Data C2 |
Data A3 | Data C3 |
Note that deleting a column will shift the remaining columns to the left. So, in the above example, deleting column B resulted in column C moving to the left.
You can also specify multiple columns to delete at once using a range:
Sub DeleteMultipleColumns() Worksheets("Sheet1").Columns("B:C").Delete End Sub
This code will delete both the second and third columns, resulting in the following data:
Column A |
---|
Data A1 |
Data A2 |
Data A3 |