我试图从D开始在每列旁边插入一个列,我的问题是列数会改变,所以我需要识别代码中的最后一列。
每当我运行以下内容时,它似乎无法正确识别最后一列。
Sub InsertColumnsv2()
Dim iLastCol As Long
Dim StartCell As Range
Set StartCell = Range("A1")
iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column
For colx = 4 To iLastCol Step 2
ActiveSheet.UsedRange
iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column
Columns(colx).Insert Shift:=xlToRight
Next colx
End Sub
答案 0 :(得分:3)
您正在两者之间添加列,iLastCol
更改,因此您需要向后循环,使用Step -1
,因为您每步都要添加一列。
注意:不要依赖ActiveSheet
,而是使用Columns
完全限定您的Cells
和With Worksheets("YourSheetName")
对象。
Option Explicit
Sub InsertColumnsv2()
Dim iLastCol As Long, colx As Long
With Worksheets("Sheet1") ' <-- change to your sheet's name
iLastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column ' get the last column for the first row
For colx = iLastCol To 4 Step -1
.Columns(colx).Insert Shift:=xlToRight
Next colx
End With
End Sub
答案 1 :(得分:3)
尝试向后运行
Sub InsertColumnsv2()
Dim iLastCol As Long
Dim colx As Long
iLastCol = Cells(1, Columns.Count).End(xlToLeft).Column
For colx = iLastCol To 4 Step -1
Columns(colx).Insert Shift:=xlToRight
Next colx
End Sub
答案 2 :(得分:1)
解决插入问题的更好方法是从完成开始到开始。
Sub InsertColumnsv2()
Dim iLastCol As Long
Dim StartCell As Range
Set StartCell = Range("A1")
iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column
For colx = iLastCol To 4 Step -1
Columns(colx).Insert Shift:=xlToRight
Next colx
End Sub