从循环遍历行的if语句返回文本值

时间:2019-04-15 08:44:46

标签: excel vba loops if-statement text

我想创建一个if函数,该函数根据D列中的行的颜色和E列中的行的百分比返回文本值。 例如。根据D6中的颜色和E6中的值,在F6中返回一个值,然后循环遍历重复此行的行。 我编写的代码可以运行,但是在Excel工作表的任何地方都没有值,这可以解决吗?

Sub Message_Click()

Set shr = ActiveWorkbook.Sheets("Report")
shr.Range("F6:F37").ClearContents

Dim rng2 As Range
Dim rng3 As Range
Set rng2 = ActiveSheet.Range("D6:D37")
Set rng3 = ActiveSheet.Range("E6:E37")

For RR = 1 To 33
Set rng2 = Cells(RR + 5, 3)
Set rng3 = Cells(RR + 5, 4)

If rng2.Interior.ColorIndex = 50 Then
    Range("F6:F37").Value = "Passed"
ElseIf rng2.Interior.ColorIndex = 38 And rng3 > 60 Then
    Range("F6:F37").Value = "Warning"
ElseIf rng2.Interior.ColorIndex = 38 And rng3 < 60 Then
    Range("F6:F37").Value = "Still has chances"
ElseIf rng2.Interior.ColorIndex = 38 And rng3 = 100 Then
    Range("F6:F37").Value = "Failed"
End If

Next
End Sub

1 个答案:

答案 0 :(得分:0)

将范围的值与数字进行比较时,它应如下所示:

rng3.value < 60

此外,请记住,您没有对颜色索引进行单元检查。因此,如果rng2中的一个单元格的颜色索引不为50,而其他所有单元格的颜色索引都为50,则此操作:

 rng2.Interior.ColorIndex = 50

将在整个范围内返回FALSE。因此,基本上,您在进行范围明智的检查。

正如评论中的某人所说,逻辑有些倒退。但是,这是一种实现方法:

Sub Message_Click()
Dim sht As Worksheet
Dim RR As Long
Set sht = ThisWorkbook.Worksheets("Report")
sht.Range("F6:F37").ClearContents
For RR = 6 To 37 Step 1
    If sht.Cells(RR, "D").Interior.ColorIndex = 50 Then
        sht.Cells(RR, "F").Value = "Passed"
    ElseIf sht.Cells(RR, "D").Interior.ColorIndex= 38 And sht.Cells(RR, "E").Value > 60 And sht.Cells(RR, "E").Value < 100 Then
        sht.Cells(RR, "F").Value = "Warning"
    ElseIf sht.Cells(RR, "D").Interior.ColorIndex= 38 And sht.Cells(RR, "E").Value < 60 Then
        sht.Cells(RR, "F").Value = "Still has chances"
    ElseIf sht.Cells(RR, "D").Interior.ColorIndex= 38 And sht.Cells(RR, "E").Value = 100 Then
        sht.Cells(RR, "F").Value = "Failed"
    Else
        sht.Cells(RR, "F").Value = "N/A"
    End If
Next RR

End Sub

这是示例结果:

enter image description here