我知道线程很旧,但我必须指出,这里最受好评的答案是有风险的,可能会给你带来严重的麻烦。我不知道它是否取决于 Excel 版本 - 我使用 Excel'16。
让我们考虑包含列的表:col A、col B 和 col C。
我们使用“The Dudes”单行代码并希望将我们的新列命名为“Col B”。它已经存在,但请检查会发生什么:
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
我们得到了什么?结果我们有 4 列:
- 可乐
- 新插入的Column1或表的列的另一个默认名称 (1)
- Col B - 用“test”字符串填充的“旧”B 列
- 科尔C
(1) 这取决于你的语言版本——我的叫做 Kolumna1,它是由 Excel 自动给出的
最糟糕的是我们在 Col B 中的数据在宏运行后丢失了。所以我建议改为使用@stenci 的逐步解决方案,或者更好地添加一些错误处理,例如:
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