Delete columns - Start End range given in another sheet

jaime1182

New Member
Joined
Dec 11, 2007
Messages
49
Office Version
  1. 2013
Platform
  1. Windows
Hi all

Hope you are all well. I am trying to work my way through a new project requirement. I need to remove columns from a sheet prior to sending it out. However, this range is often a variable. I want to use the value in the B2 and B3 cells to form the range to be used in the macro.

VBA Code:
Sub DeleteColumns()
    Dim StartCol As Long
    Dim LastCol As Long

    StartCol = Sheets("Sheet1").Range("B2").Value
    LastCol = Sheets("Sheet1").Range("B3").Value
    
    Sheets("Sheet2").Select
    Columns(StartCol : LastCol).EntireColumn.Delete

End Sub

In other words, if B2 and B3 are 5 and 11 respectively, columns E to K are to be deleted.

However, I am having trouble getting this part to actually work:
Code:
Columns(StartCol : LastCol).EntireColumn.Delete

Did I 'dim' it wrongly? Should I be using numbers or should I be using the column names (ie E etc)?

Much thanks in advance
 

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
MAybe like this
VBA Code:
Sub DeleteColumns()
    Dim StartCol As Integer, LastCol As Integer
    StartCol = Sheets("Sheet1").Range("B2").Value
    LastCol = Sheets("Sheet1").Range("B3").Value
    Sheets("Sheet2").Select
    Range(Columns(StartCol), Columns(LastCol)).Delete
End Sub
 
Upvote 0
Solution
Define range by first cell and last cell, like this:
VBA Code:
Range(Cells(1, StartCol), Cells(1, LastCol)).EntireColumn.Delete
 
Upvote 0
Both solutions are great! Thank you so much everyone! That just saved me a week of headaches and painful eyes!

Much appreciated!
 
Upvote 0

Forum statistics

Threads
1,214,987
Messages
6,122,614
Members
449,090
Latest member
vivek chauhan

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top