'How to insert a column in Excel using VBA?
Please help me with the code to insert a column in excel using vba. Here is what I am doing -
Sheet1.Range("A:A").EntireColumn.insert
Solution 1:[1]
That code works fine for me.
Sheet1.Range("A:A").Insert
works also. Range("A:A")
is already referencing an EntireColumn
.
There are a few things to check if it's not working for you:
- You're referencing an object called
Sheet1
. Is that definitely the codename of the worksheet you want to change? Make sure you understand the difference between sheet name and codename. You could try referencing it by the sheet's name instead:Worksheets("Tabname").Range("A:A")...
- Is the worksheet protected? That would give you an error if it is.
- Is there any data in the right-most column of the spreadsheet? That would also cause an error as Excel doesn't know what to do with it. If you're not 100% sure, select the entire right-most column of the sheet and hit delete to remove anything that might cause an issue.
- Lastly, can you insert a column manually? i.e. select left most column, [right-click] and [Insert]?
Solution 2:[2]
I think you got the Sheets
property wrong, this works for me :
Sheets(1).Range("A:A").EntireColumn.Insert
Solution 3:[3]
You should clearly mention what you are trying to do; what type of problem you are facing.
However, you should try out the below code. hope this will help
Sheet1.Range("A:A").EntireColumn.Insert Shift:=xlToRight
while inserting a new row or column make sure to refer to the entire row or column. Check if there are any marge cells at the right of column A. That can possibly be causing the problem.
Solution 4:[4]
Sub TryMe()
Columns(1).Insert
End Sub
Also, this is a very generic question. If you can Google something and figure it out in a fraction of the time that it takes to craft a question and post it on SO, just Google it. If your question is very unique, and after hitting multiple dead ends using Google, then ask the SO community. I found the 3 links below using a Google search that took around 1 second.
https://www.automateexcel.com/vba/insert-row-column/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | CLR |
Solution 2 | Guillaume G |
Solution 3 | Mukibul Hasan |
Solution 4 | ASH |