Excel表格:添加空白列和标题vba

我有一个Excel表,我想添加一个列,然后命名标题。 不知何故,我的旧代码不工作了,我不知道是否有任何与我做一个表的数据范围(名称是Table1)。 现在代码运行没有错误,但只添加空白列,但没有添加标题。 我按F8 ,它看起来像跳过select部分,跳转到最后。

表格从列A到列AG中指定。 我曾经能够插入多个空白列,并添加头文件就好了。 现在我不想指定单元格的位置,并为它指定一个单元格值( cell(1, 32).value ="Month" ),因为我想要添加灵活性,但是需要添加许多列,并添加标题分别像以前一样。

 Sub Ins_Blank_Cols_Add_Headers() Columns("AF:AG").Insert Shift:=xlToRight Columns("AF:AF").Cells(1, 1) = "<<NewHeader>>" Columns("AG:AG").Cells(1, 1) = "<<NewHeader>>" Dim cnter As Integer LastCol = Cells(1, Columns.Count).End(xlToLeft).Column cnter = 0 For i = 1 To LastCol If Cells(1, i) Like "<<NewHeader>>*" Then Select Case cnter Case 0: Cells(1, i).Value = "Month" Case 1: Cells(1, i).Value = "Year" End Select cnter = cnter + 1 End If Next i 

结束小组

停止使用Range.SelectSelection ,它会对你有好处。


也总是使用完全合格的范围。


你的问题是,当你在表格中插入一列时,Excel会自动为它分配一个标题名称。

所以你的IF条件检查空失败。 因此没有select案例调用


改变这一点

 Columns("AF:AF").Select Selection.Insert Shift:=xlToRight 

  Columns("AF:AF").Insert Shift:=xlToRight Columns("AF:AF").Cells(1, 1) = "<<NewHeader>>" ' In Table Can't set blank header so use a place holder. 

还要更改If条件

 If IsEmpty(Cells(1, I)) Then 

  If Cells(1, I) Like "<<NewHeader>>*" Then