I\'m running into some issues on a worksheet that I\'m building. I want to insert a column at a specific location in a table and then set the header.
I searched aro
I know the thread is old, but I must point out that the most upvoted answer here is risky and can get you in a serious trouble. I don't know if it depends Excel version - I use Excel'16.
Let's consider table containing columns: col A, col B and col C.
We use "The Dudes" one-liner code and want to name our new column "Col B". It already exists but check what happens:
Sub theDude()
Dim Table As ListObject
Set Table = ActiveSheet.ListObjects(1)
With Table
' adding column on the second place
' and trying to force its header to "Col B"
.ListColumns.Add(2).Name = "Col B"
'fill "Col B" with value
.ListColumns("Col B").DataBodyRange = "test"
End With
End Sub
And what we get? In result we have 4 columns:
(1) it depends on yours language version- mine is called Kolumna1 and it's given by Excel automatically
The worst thing is our data in Col B is lost after macro run. So I would suggest instead one-liner (methods chaining) use @stenci's step by step solution, or even better add some error handling e.g.:
Sub AddingColumn()
Dim Table As ListObject
' ActiveSheet just for test
Set Table = ActiveSheet.ListObjects(1)
Dim newColName As Variant ' or string / long
newColName = "Col B"
If headerExists(newColName, Table) Then
Dim tit As String: tit = "Error"
Dim txt As String
txt = "Header " & newColName & " already exists. Macro will be interrupted"
MsgBox txt, vbOKOnly, tit
Exit Sub
Else
' main code goes here *********************
With Table
' adding column on the second place
' and trying to force its header to "Col B"
.ListColumns.Add(2).Name = newColName
'fill "Col B" with value
.ListColumns("Col B").DataBodyRange = "test"
End With
End If
End Sub
Function headerExists(ByVal findHeader As String, ByVal tbl As ListObject) As Boolean
Dim pos As Variant ' position
pos = Application.Match(findHeader, tbl.HeaderRowRange, 0)
headerExists = Not IsError(pos)
End Function