Excel VBA – 插入行和插入列macros

我有一个使用列A:J显示和计算任务信息的“任务跟踪器”工作簿(A:E是用户input的数据,F:J包含使用C:E中的信息并执行计算的公式)F: J是用户视图中的隐藏单元格。)其余列显示任务落在时间轴上的热图,以及它们是否按时运行,落后或已完成。

有两个button供用户使用:一个插入一个新的行,一个插入一个新的列。 InsertRow()macros在列表中插入一行,然后从上面的行中复制公式。 InsertColumn()macros定位工作表中最后使用的列,并将所有内容从列的左侧复制到其左侧。

最初,我有一个使用从列F(公式开始)拷贝到列XFD的Range的InsertRow的macros。 但是,一旦我创build了InsertColumnmacros,我意识到我不能这样做InsertRow,因为InsertColumn需要在工作表中find最后一个包含数据的列,并在右边添加一个新的…如果InsertRow首先运行,则InsertColumn将不起作用,因为lastColumn的值将作为列XFD的索引返回。

我正在寻找帮助:我需要在InsertRowmacros中findlastColumn值,然后在程序执行代码的复制/粘贴部分时,将该值作为Range的一部分。 我认为我遇到的问题与我用来查找最后一列的代码返回索引有关,而Range函数需要该列的名称。

下面是我对这两个macros的看法:

Sub InsertTaskRow() ' InsertTaskRow Macro ' ' This macro inserts a new row below whatever role the user currently has selected, then ' copies the formulas and formatting from above down to the new row Dim lastColumn As Long Dim currrentRow As Long Dim newRow As Long lastColumn = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Column currentRow = ActiveCell.Row newRow = currentRow + 1 ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown Range("F" & currentRow & ":" & lastColumn & currentRow).Copy Destination:=Range("F" & newRow & ":" & currentRow & newRow) End Sub Sub InsertColumn() ' InsertColumn Macro ' ' This macro copies the formulas and formatting from the last data-containing column ' in the worksheet, and pastes it into the next column to the right. Dim lastColumn As Long lastColumn = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Column MsgBox lastColumn Columns(lastColumn).Copy Destination:=Columns(lastColumn + 1) End Sub 

你可以尝试改变你的lastColumn发生如下:

 lastColumn = ActiveSheet.Range("A1").End(xlToRight).Column 

这将扩展你的范围到所有使用的单元格。 我尝试了使用clCellTypeLastCell,但它没有明显的原因拉过了必要的; 即使在删除了所声明的整个专栏之后也是适用的。 只是一个简要的说明,在使用Range()时,使用索引或列名是没有问题的 – 甚至可以互换,它们都是完全合格的。