在工作表VBA上插入值之前或之后更改整行的颜色

时间:2013-11-01 19:12:21

标签: excel vba excel-vba

我正在尝试在确定条件发生时更改行的值,并且我想在插入完成后执行此操作,但也许在插入之前更容易(?)我尝试过的事情两者,我做错了因为它不起作用

代码:

With ThisWorkbook.Worksheets("Site Configuration List")
       ' Tried this .Range("A").EntireRow.Interior.Color = 49407
        .Range("A" & Rows.Count).End(xlUp).Offset(1).Value = Code
        .Range("B" & Rows.Count).End(xlUp).Offset(1).Value = Name
        .Range("C" & Rows.Count).End(xlUp).Offset(1).Value = "" & Contract & ""
        .Range("D" & Rows.Count).End(xlUp).Offset(1).Value = SiteCode
        .Range("E" & Rows.Count).End(xlUp).Offset(1).Value = SiteName
        .Range("G" & Rows.Count).End(xlUp).Offset(1).Value = Approver
        .Range("K" & Rows.Count).End(xlUp).Offset(1).Value = ItemCode
        .Range("M" & Rows.Count).End(xlUp).Offset(1).Value = RequiredQty
        .Range("N" & Rows.Count).End(xlUp).Offset(1).Value = ControlFlag
    If Color = 0 Then
       ', this .Offset(-1).Interior.Color = 49407
        ',this .Interior.Color = 49407
     'and this .EntireRow.Interior.Color = 255
    Else


    End If
    End With

显然不是在同一时间,但没有那些工作。我做错了什么,我该如何解决?我是VBA的新手,一些最简单的事情通常需要我更多的时间来弄明白。我用过的是为了达到我想要的目的,我从其他类似的问题中得到了它。实现上面代码的sub的调用是在一个循环中,然而,对于我尝试过的每一件事,当它到达该行时程序就停止了。没有错误或任何事情。

2 个答案:

答案 0 :(得分:2)

范围未正确声明。而不是

.Range("A").EntireRow.Interior.Color = 49407

它需要

.Range("1:1").EntireRow.Interior.Color = 49407

如果你想高亮整行或

.Range("A:A").EntireColumn.Interior.Color = 49407

突出显示整个列。

修改

要为最后一行数据着色,您需要使用Rows方法,以及从Rows.Count获得的最后一行的数字。代码如下所示

Rows(Range("A" & Rows.Count).End(xlUp).Row).EntireRow.Interior.Color = 49407

或者

Rows(Range("A" & Rows.Count).End(xlUp).offset(1).Row) _
                                           .EntireRow.Interior.Color = 49407

答案 1 :(得分:2)

按照以下方式更改代码应该可以解决问题。

With ThisWorkbook.Worksheets("Site Configuration List")
    .Range("A" & Rows.Count).End(xlUp).Offset(1).EntireRow.Interior.Color = 49407
    .Range("A" & Rows.Count).End(xlUp).Offset(1).Value = Code
    .Range("B" & Rows.Count).End(xlUp).Offset(1).Value = Name