繁体   English   中英

插入新行VBA宏

[英]Insert New Row VBA Macro

我想使用VBA宏在MS Excel中插入新行,并且还要修改新行中特定单元格的背景颜色(即Interior.ColorIndex)。

我正在使用ActiveCell.Offset(1).EntireRow.Insert在活动单元格下面插入新行,但是我不确定如何更改新行中特定单元格的背景颜色。

例如:

如果插入新行(即第4行),我想将单元格B4C4的背景颜色更改为灰色。

非常感激任何的帮助!

问候

马丁

这样做:

Sub insertRowAndHighlightCells()

    Dim rng As Range
    Dim rw As Long

    With ActiveCell
        rw = .Row
        .Offset(1).EntireRow.Insert
    End With

    Set rng = Rows(rw + 1)
    rng.Columns("B:C").Interior.Color = RGB(191, 191, 191)

End Sub

编辑

一个更简单的版本:

Sub insertRowAndHighlightCells()

    Dim rw As Long

    With ActiveCell
        rw = .Row
        .Offset(1).EntireRow.Insert
    End With

    Rows(rw + 1).Columns("B:C").Interior.Color = RGB(191, 191, 191)

End Sub

为什么不使用您用来插入行的activecell.offset(1,0)?

例如

Sub test()
    ActiveCell.Offset(1, 0).EntireRow.Insert shift:=xlDown
    ActiveSheet.Cells(ActiveCell.Offset(1, 0).Row, 2).Interior.ColorIndex = 15
    ActiveSheet.Cells(ActiveCell.Offset(1, 0).Row, 3).Interior.ColorIndex = 15
    'Alternatively:
    Dim colorRow as integer
    colorRow = ActiveCell.Offset(1,0).Row 'The inserted row)
    ActiveSheet.Range("B" & colorRow & ":C" & colorRow).Interior.ColorIndex = 15

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM