簡體   English   中英

Excel VBA-插入行和插入列宏

[英]Excel VBA - Insert Row & Insert Column Macros

我有一本“任務跟蹤程序”工作簿,該工作簿使用A:J列顯示和計算任務信息(A:E用於用戶輸入的數據,F:J包含使用C:E中的信息並執行計算的公式。 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

您可以嘗試將lastColumn更改為以下內容:

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

這會將您的范圍擴展到所有使用過的單元格。 我嘗試使用clCellTypeLastCell,但是由於沒有明顯的原因,它超出了必要的范圍。 即使刪除它聲稱的所有列也適用。 僅供參考,在使用Range()時使用索引或列名沒有問題-甚至可以互換,它們都完全合格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM