【问题标题】:Excel VBA - Insert Row & Insert Column MacrosExcel VBA - 插入行和插入列宏
【发布时间】:2014-02-17 16:03:39
【问题描述】:

我有一个“任务跟踪器”工作簿,它使用 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

【问题讨论】:

    标签: vba excel


    【解决方案1】:

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

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

    这会将您的范围扩展到所有使用的单元格。我尝试使用 clCellTypeLastCell,但没有明显的原因它超出了必要的范围;即使删除了它声称适用的整个列。仅供参考,在使用 Range() 时使用索引或列名没有问题 - 即使可以互换,它们都是完全限定的。

    【讨论】:

    • 谢谢。我尝试使用该代码来定位最后一列,但不是找到最后一列 used 它返回工作表中的最后一列。
    • 因为第1行的数据是空的:xlToRight需要在有数据的时候去第一个空单元格,或者空的时候去第一个数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多