Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add columns in excel

Tags:

excel

vba

I am trying to create an excel macro that automatically inserts two columns before column D... The procedure worked fine when I created it, here it is:

Sub AddColumns()
    Columns("D:D").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub

But when I open my worksheet and try it out, all my data is pushed to the right about 11 columns and 11 blank columns are inserted. I'm sure this has to with some rows having 11 columns merged. The Select statements selects the first 11 columns A-K.

How do I fix this?

like image 893
user1634700 Avatar asked Feb 13 '23 14:02

user1634700


1 Answers

It happens because of the line Columns("D:D").Select. If you don't select this columns code would work fine.

Use this one instead:

With Range("D:D")
    .Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    .Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End With

And, How to avoid using Select/Active statements:)

like image 54
Dmitry Pavliv Avatar answered Feb 22 '23 15:02

Dmitry Pavliv