Excel宏:使用Excel Excel检查数据和着色

时间:2013-09-26 19:31:35

标签: excel-vba vba excel

我在sheet2中有一个列“C”,可以有3个标准值说(是,否,NA)说到第100行。现在在Sheet1列G5& G6,我想根据以下条件输出结果。条件1-如果Sheet2 C列中的所有值均为Yes / NA,则G5中的输出值应为YES,背景为绿色,如果存在NO,则值为NO,G6为红色。 条件2-如果Sheet2 C列中的所有值均为No / NA,则G6中的输出值应为NO,背景为红色。

1 个答案:

答案 0 :(得分:0)

尝试一下:

Sub YesNoCheck()
    Dim s1 As Worksheet, s2 As Worksheet
    Dim rCheck As Range
    Set s1 = Sheets("Sheet1")
    Set s2 = Sheets("Sheet2")
    Dim wf As WorksheetFunction
    Set wf = Application.WorksheetFunction
    Set rCheck = s2.Range("C1:C100")
    s1.Range("G5:G6").Clear
    If wf.CountIf(rCheck, "No") = 0 Then
        s1.Range("G5").Value = "Yes"
        s1.Range("G5").Interior.ColorIndex = 10
        Exit Sub
    End If
    If wf.CountIf(rCheck, "Yes") = 0 Then
        s1.Range("G6").Value = "No"
        s1.Range("G6").Interior.ColorIndex = 3
    End If
End Sub

修改#1

我的错误,请改用:

Sub YesNoCheck2()
    Dim s1 As Worksheet, s2 As Worksheet
    Dim rCheck As Range
    Set s1 = Sheets("Sheet1")
    Set s2 = Sheets("Sheet2")
    Dim wf As WorksheetFunction
    Set wf = Application.WorksheetFunction
    Set rCheck = s2.Range("C1:C100")
    s1.Range("G5:G6").Clear
    If wf.CountIf(rCheck, "Yes") + wf.CountIf(rCheck, "NA") = 100 Then
        s1.Range("G5").Value = "Yes"
        s1.Range("G5").Interior.ColorIndex = 10
    End If
    If wf.CountIf(rCheck, "No") + wf.CountIf(rCheck, "NA") = 100 Then
        s1.Range("G6").Value = "No"
        s1.Range("G6").Interior.ColorIndex = 3
    End If
End Sub

一位看着我肩膀的朋友指出,如果所有条目都是“NA”,那么这两个条件都可能是真的!!