我有一个excel表,我想向其中添加一列,然后命名标题。不知何故,我的旧代码不再起作用,并且我不确定是否将数据范围设为表(名称为Table1)与我有任何关系。现在,代码运行正常,没有错误,只添加了空白列,而没有添加标题。我按F8键,它看起来像跳过“选择”部分,然后跳到结尾。
表从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.Select
和Selection
,对您有好处。
还请始终使用完全合格的范围。
您的问题是,当您在表中插入一列时,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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句