Excel VBA - 插入行和放大器插入列宏

时间:2014-02-17 16:03:40

标签: excel vba excel-vba

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

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

最初,我有一个使用Range的InsertRow宏,它从列F(公式开始处)复制到列XFD。但是,一旦我创建了InsertColumn宏,我意识到我不能像那样执行InsertRow,因为InsertColumn需要在工作表中找到最后一个包含数据的列并在右边添加一个新的...如果InsertRow首先运行,则InsertColumn将无效,因为lastColumn的值将作为列XFD的索引返回。

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

以下是我对两个宏的看法:

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

1 个答案:

答案 0 :(得分:1)

您可以尝试将lastColumn出现更改为以下内容:

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

这会将您的范围扩展到所有使用过的细胞。我尝试使用clCellTypeLastCell,但它没有明显的原因而进一步拉动;即使删除了它声称适用的整个列。仅仅是一个FYI,使用Range()时使用索引或列名称没有问题 - 即使是可互换的,它们都是完全合格的。