当任何一个单元格值文本为" Not Executed"时,将文本插入Excel单元格。在Excel VBA中

时间:2018-05-21 12:54:41

标签: excel-vba vba excel

当所有范围都是PASS时,以下代码工作正常。但我想要范围示例中的任何一个:G5 is "Not Executed"然后我想插入SQL Error

   Sub Test()

     If Worksheets("Before Conversion German Count").Range("G4:G80").Text = "PASS" Then
            Worksheets("INDEX").Range("F30") = "Completed"
         Worksheets("INDEX").Range("F30").Interior.ColorIndex = 43
 ElseIf Worksheets("Before Conversion German Count").Range("G4:G80").Text = "Not Executed" Then
          Worksheets("INDEX").Range("F30") = "SQL Error"
         Worksheets("INDEX").Range("F30").Interior.ColorIndex = 44
  Else: Worksheets("INDEX").Range("F30") = "Validation failed"
       Worksheets("INDEX").Range("F30").Interior.ColorIndex = 3
  End If

  End Sub

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

我认为以下内容符合您的要求:

With Worksheets("INDEX").Range("F30")
    If Not (Worksheets("Before Conversion German Count").Range("G4:G80").Find("Not executed") Is Nothing) Then
        .Value = "SQL Error"
        .Interior.ColorIndex = 44
    ElseIf (Worksheets("Before Conversion German Count").Range("G4:G80").Find("PASS") Is Nothing) Then
        .Value = "Validation failed"
        .Interior.ColorIndex = 3
    Else
        .Value = "Completed"
        .Interior.ColorIndex = 43
    End If
End With

这将启动指向输出单元格的With

然后它会对范围执行FIND,因此如果它可以看到 Not Executed 的1个实例,那么您将获得“SQL Error”输出。< / p>

然后它会查找 PASS ,如果没有找到,则输出“验证失败”

否则,输出“已完成”

然后关闭WITH

我认为这个逻辑符合您的意图,但您可以根据自己的意愿进行调整。

答案 1 :(得分:0)

正如我在评论中所建议的那样,让我们​​使用COUNTIF

Sub Result()
Const PASS = "PASS"
Const NOT_EXECUTED = "Not Executed"
Dim rg As Range

    Set rg = Worksheets("Before Conversion German Count").Range("G4:G80")

    With Worksheets("INDEX").Range("F30")
        If WorksheetFunction.CountIf(rg, PASS) = rg.Rows.Count Then
            .Value = "Completed"
            .Interior.ColorIndex = 43
        ElseIf WorksheetFunction.CountIf(rg, NOT_EXECUTED) = rg.Rows.Count Then
            .Value = "SQL Error"
            .Interior.ColorIndex = 44
        Else
            .Value = "Validation failed"
            .Interior.ColorIndex = 3
        End If
    End With

End Sub