2015-09-04 66 views
1

我想编写这个程序,突出全行重视,其中有“N”在各自的排列N内的值突出显示所有行等于在细胞foobar的

我不是太熟悉编码VBA的格式,我不能让这个程序的功能

Sub highlight_new_pos() 

Dim rng As Range, lCount As Long, LastRow As Long 
Dim cell As Object 

With ActiveSheet 'set this worksheet properly! 
    LastRow = .Cells(Rows.Count, 1).End(xlUp).Row 
    For Each cell In .Range("N2:N" & LastRow) 
     If cell = "N" Then 
      With Selection.Interior 
       .Pattern = xlSolid 
       .PatternColorIndex = xlAutomatic 
       .Color = 65535 
       .TintAndShade = 0 
       .PatternTintAndShade = 0 
      End With 

    Next cell 
End With 


End Sub 
+1

[条件格式](https://support.office.com/zh-cn/article/Use-a-formula-to-apply-conditional-formatting-fed60dfa-1d3f- 4e13-9ecb-f1951ff89d7f)与本地工作表公式(例如'= $ N1 =“N”')是更好的解决方案。 – Jeeped

+0

可能ColumnN比ColumnA有更多的条目? – pnuts

+0

@pnuts - tbh,我从不使用任何预先制定的规则。我更喜欢提供适用的公式。 – Jeeped

回答

1

在代码中,你是通过细胞循环,但你还是改变了最初的选择(在循环中的细胞没有)的颜色。调整如下:

Sub highlight_new_pos() 

Dim rng As Range, lCount As Long, LastRow As Long 
Dim cell As Object 

With ActiveSheet 'set this worksheet properly! 
    LastRow = .Cells(Rows.Count, 1).End(xlUp).Row 
    For Each cell In .Range("N2:N" & LastRow) 
     If cell = "N" Then 
      With cell.Interior 
       .Pattern = xlSolid 
       .PatternColorIndex = xlAutomatic 
       .Color = 65535 
       .TintAndShade = 0 
       .PatternTintAndShade = 0 
      End With 
     End if 
    Next cell 
End With 


End Sub 

如果你想整行,改变cell.Interiorcell.entirerow.Interior

+1

错过了一个结束,就像原始代码 – nutsch

1
Option Explicit 

Sub highlight_new_pos() 
    Dim cel As Object 

    With ActiveSheet 
     For Each cel In .Range("N2:N" & .Cells(.Rows.Count, 14).End(xlUp).Row) 
      If UCase(cel.Value2) = "N" Then cel.Interior.Color = 65535 
     Next 
    End With 
End Sub 

这将是更快,如果你有很多行:

Sub highlight_new_pos1() 
    Application.ScreenUpdating = False 
    With ActiveSheet 
     With .Range("N1:N" & .Cells(.Rows.Count, 14).End(xlUp).Row) 
      .AutoFilter Field:=1, Criteria1:="N" 
      .Offset(1, 0).Resize(.Rows.Count - 14, .Columns.Count).Interior.Color = 65535 
      .AutoFilter 
     End With 
    End With 
    Application.ScreenUpdating = True 
End Sub 
+1

我认为'End(xlUp)'行中的'1'会比'14'更好,但+1(尽管还提到了'row'而不是' cell')。 – pnuts

+1

谢谢@pnuts:它更好,我更新了它(不确定数据,如果整行需要突出显示) –