首页 > 解决方案 > 从遍历行的 if 语句返回文本值

问题描述

我想创建一个 if 函数,该函数根据 D 列中的行颜色和 EEg 列中的行百分比返回文本值,具体取决于 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

标签: excelvbaloopsif-statementtext

解决方案


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

rng3.value < 60

另外,请记住,您没有对颜色索引执行单元格检查。因此,如果 rng2 中的一个单元格的颜色索引不是 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

这是示例结果:

在此处输入图像描述


推荐阅读