在表Excel VBA中插入新列

时间:2013-07-09 13:46:33

标签: excel vba excel-vba

我在我正在构建的工作表上遇到了一些问题。我想在表格中的特定位置插入一列,然后设置标题。

我搜了一会儿,找到了(某些版本)以下代码:

ActiveSheet.Columns(2).Insert

这适用于插入列,但我不确定如何在此之后更改表的标题。

另外,我之前在这里有一些建议,可以在表格的末尾添加列并命名它们。

代码是:

Dim oSh As Worksheet
Set oSh = ActiveSheet
Dim oLc As ListColumn
Set oLc = oSh.ListObjects("PropTable").ListColumns.Add

oLc.Name = "XYZ"

我尝试以各种方式结合这两种方法,但我没有运气。有没有办法修改第二个代码块,以便在特定位置插入一列,而不是只添加一列?

感谢。

-Sean

3 个答案:

答案 0 :(得分:11)

可以使用相同的代码行向特定位置的表中添加列并命名。

Table.ListColumns.Add(2).Name = "New Header"

这将在表格的第二列左侧添加一列,并将其命名为New Header。 您可以通过在您知道其名称的列的左侧添加一列来使您的代码动态化。这样,就没有必要指定新列的固定位置的整数值。

Dim newColNum as Integer
newColNum = Range("Table[Column Name]").Column
Table.ListColumns.Add(newColNum).Name = "New Header"

[列名]是表中要插入新列的列的名称。它可以在表中有任何位置,您可以将它的值作为整数传递给Add。

答案 1 :(得分:5)

  Dim Table As ListObject
  Set Table = Sheet1.ListObjects("Table1")
  Table.ListColumns.Add 2
  Table.HeaderRowRange(2) = "New header"

答案 2 :(得分:0)

我知道线程很旧,但是我必须指出,在这里最不赞成的答案很冒险,可能会给您带来严重的麻烦。我不知道这是否取决于Excel版本-我使用的是Excel'16。

让我们考虑包含以下列的表:col A,col B和col C。

before macro

我们使用“ 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
  • 新插入的 Column1 或表的列的另一个默认名称(1)
  • Col B-充满“测试”字符串的“旧” B列
  • Col C

after macro

(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
相关问题