vba delete columns with variable

storemannequin

Board Regular
Joined
May 29, 2010
Messages
108
I've written this below code to and am getting an error on the last line, I think the syntax is wrong. I'm trying to delete columns H to the variable set to final column minus 6 columns.

Sub Macro2()
'
' Macro2 Macro
'

'
FC = Cells(1, Columns.Count).End(xlToLeft).Column - 6


Rows("1:8").Delete Shift:=xlUp
Columns("F:F").Delete Shift:=xlToLeft
Columns("H:H" & ":" & FC).Delete Shift:=xlToLeft
End Sub
 

Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off
Try

Code:
Sub Macro2()
'
' Macro2 Macro
'

'
FC = Cells(1, Columns.Count).End(xlToLeft).Column - 6


Rows("1:8").Delete Shift:=xlUp
Columns("F").Delete
Range(Cells(1, 8), Cells(1, FC)).EntireColumn.Delete
End Sub
 
Upvote 0
This worked for me

Code:
Sub Macro2()
'
' Macro2 Macro
'

'
Dim FC As Long
FC = Cells(1, Columns.Count).End(xlToLeft).Column - 6


Rows("1:8").Delete
Range(Cells(1, 8), Cells(1, FC)).EntireColumn.Delete
Columns("F").Delete
End Sub
 
Upvote 0
Maybe

Code:
Sub Macro2()
'
' Macro2 Macro
'

'
Dim FC As Long, i As Long
FC = Cells(1, Columns.Count).End(xlToLeft).Column - 6


Rows("1:8").Delete
For i = FC To 8 Step -1
    Columns(i).Delete
Next i
Columns("F").Delete
End Sub
 
Upvote 0
If FC is less than 8 the loop won't run.

Similarly, if FC is less than 8 then the previous code would error.
 
Upvote 0

Forum statistics

Threads
1,224,599
Messages
6,179,831
Members
452,946
Latest member
JoseDavid

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