首页 文章

Excel VBA - 插入行和插入列宏

提问于
浏览
2

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

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

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

What I am looking for help with: 我需要在InsertRow宏中找到lastColumn值,然后在程序执行代码的Copy / Paste部分时将该值用作Range的一部分 . 我认为我用'm having has to do with the fact that the code I'找到最后一列的问题会返回索引,而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 回答

  • 1

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

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

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

相关问题