CluelessAboutExcel
New Member
- Joined
- Dec 6, 2021
- Messages
- 5
- Office Version
- 2016
- Platform
- Windows
Hi,
I have been working on a VBA formula to insert columns to a table based on an integer entry in one cell. So far I have managed to get it to work but as there are multiple categories of columns to add, I need to input the column numbers in a certain order as the columns are inserted based on excel column indexes (The columns will insert at the same place every time which could be wrong if there have already been new columns added). I want to code it so that VBA looks up a certain string value in a cell across a row and enters the new column with respect to that. After this, I want to name the new inserted columns with an increasing category number (i.e. country1, country2, etc.) This is what I have got so far:
The problem is with the line using the range as cells with category 1 as it comes up with a "Method 'Range' of object '_Global' failed" error message but I couldn't figure out how else to put a string value of a cell in a row into the range expression.
In addition to this, the line below naming the new column has a range which is relative to the new column input position (G15), if this could be done more efficiently that would be useful to know!
Any help would be massively appreciated!
I have been working on a VBA formula to insert columns to a table based on an integer entry in one cell. So far I have managed to get it to work but as there are multiple categories of columns to add, I need to input the column numbers in a certain order as the columns are inserted based on excel column indexes (The columns will insert at the same place every time which could be wrong if there have already been new columns added). I want to code it so that VBA looks up a certain string value in a cell across a row and enters the new column with respect to that. After this, I want to name the new inserted columns with an increasing category number (i.e. country1, country2, etc.) This is what I have got so far:
VBA Code:
Sub Add_Column()
Dim aCount As Integer
Dim a As Integer
Dim bCol As Long
Dim b As Long
aCount = Range("B12").Value
bCol = Cells(15, Columns.Count).End(xlToLeft).Column
For a = 1 To aCount - 1
For b = 1 To bCol
Range(Cells(15, b).Value = "Category 1").Offset(0, 1).Insert Shift:=xlToRight
Range("G15").Value = "Category" + Str(aCount - a + 1)
Next b
Next a
End Sub
The problem is with the line using the range as cells with category 1 as it comes up with a "Method 'Range' of object '_Global' failed" error message but I couldn't figure out how else to put a string value of a cell in a row into the range expression.
In addition to this, the line below naming the new column has a range which is relative to the new column input position (G15), if this could be done more efficiently that would be useful to know!
Any help would be massively appreciated!