简体   繁体   English

插入新行VBA宏

[英]Insert New Row VBA Macro

I want to insert a new row in MS Excel using a VBA macro and also modify the background color (ie Interior.ColorIndex) of specific cells in the new row. 我想使用VBA宏在MS Excel中插入新行,并且还要修改新行中特定单元格的背景颜色(即Interior.ColorIndex)。

I am using ActiveCell.Offset(1).EntireRow.Insert to insert a new row below the active cell, but I am unsure how to change the background color of specific cells in the new row. 我正在使用ActiveCell.Offset(1).EntireRow.Insert在活动单元格下面插入新行,但是我不确定如何更改新行中特定单元格的背景颜色。

For example: 例如:

If I inserted a new row (ie row 4) I would like to change the background color of cell B4 and C4 to be grey. 如果插入新行(即第4行),我想将单元格B4C4的背景颜色更改为灰色。

Any help would be most appreciated! 非常感激任何的帮助!

Regards 问候

Martin 马丁

This will do it: 这样做:

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

Edit 编辑

An even simpler version: 一个更简单的版本:

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

Why not use the activecell.offset(1,0) that you used to insert the row? 为什么不使用您用来插入行的activecell.offset(1,0)?

Eg 例如

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