我知道这个帖子已经很老了,但是我必须指出,在这里最受赞的答案是有风险的,可能会让你陷入严重的麻烦。我不知道它是否取决于Excel版本——我使用的是Excel'16。
让我们考虑包含列A、列B和列C的表格。
![before macro](https://istack.dev59.com/7Vt0Q.webp)
我们使用“ 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列:
- 列A
- 新插入的列1或表格列的另一个默认名称(1)
- 列B - 旧的B列填充了"test"字符串
- 列C
![after macro](https://istack.dev59.com/qSWcP.webp)
(1) 这取决于你的语言版本 - 我的称为Kolumna1,它是由Excel自动给出的。
最糟糕的是,在宏运行后我们在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
Range("Table1").ListObject.ListColumns.Count
。它看起来像是一个命名范围,并且可以通过ListObject
属性访问。 - stenciSet sLc = sSh.ListObjects("PropTable").ListColumns.Add(2)
- detroitwillyRange("Table1[ColName]")
指的是整个列范围。 - stenci