VBA 循环 2 个范围并对两个范围中的值应用 IF 语句

标签 vba excel

我对 excel VBA 比较陌生,我正在尝试编写一个代码来检查几个值并突出显示与 IF 语句匹配的值。

在表中,我需要循环遍历两个不同范围内的所有值,一个范围的值是日期,另一个范围的值是几个不同的字符串,并突出显示(橙色)与以下要求相对应的行:(1) 第一个范围值 >= 到今天的日期,(2) 第二个范围值 =“样本收据”。我还需要循环遍历日期范围的所有值,并突出显示(黄色)与 vale > 今天日期对应的行。表格中不符合这些要求的所有其他行都需要以浅蓝色突出显示。

我的第一个代码(如下所示)有点有效,但它突出显示了第二个范围 =“样本收据”的所有值。

Dim LastRow As Long
Dim cell As Range
Dim cell2 As Range
Worksheets("Sheet3").Activate

With ActiveSheet

 LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
 For Each cell In Range("K3:K" & LastRow)
     If cell.Value >= Date Then
        cell.Range("A1:K1").Offset(0, -10).Interior.ColorIndex = 6
     ElseIf cell.Value >= Date - 7 Then
            For Each cell2 In Range("H3:H" & LastRow)
                If cell2.Value = "Sample Receipt" Then
                 cell2.Range("A1:K1").Offset(0, -7).Interior.ColorIndex = 45
                Else
                 cell2.Range("A1:K1").Offset(0, -7).Interior.Color = RGB(220, 230, 242)
                End If
            Next
     Else
        cell.Range("A1:K1").Offset(0, -10).Interior.Color = RGB(220, 230, 242)
     End If
 Next
End With

我想不出另一种方法来设置 For 循环来满足我的需要,并且我已经环顾四周。

最佳答案

类似这样的事情:

Sub TT()
    Dim sht As Worksheet
    Dim LastRow As Long
    Dim cell As Range
    Dim dt, txt
    Dim clr As Long

    Set sht = Worksheets("Sheet3")
    LastRow = sht.Cells(.Rows.Count, "A").End(xlUp).Row

    For Each cell In sht.Range("K3:K" & LastRow).Cells

        dt = cell.Value
        txt = cell.Offset(0, -3).Value

        'don't follow your original logic so
        '  this is just an example....
        If dt >= Date And txt = "Sample Receipt" Then
           clr = vbRed
        ElseIf dt >= Date - 7 Then
           clr = vbYellow
        Else
           clr = RGB(220, 230, 242) 'default color
        End If

        cell.EntireRow.Cells(1).Color = clr

    Next

End Sub

关于VBA 循环 2 个范围并对两个范围中的值应用 IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31992622/

相关文章:

Excel DNA - 我可以避免一起重高潮吗?

excel - vba中的应用程序定义或对象定义错误

vba - 将范围设置为 "False"并根据值更改单元格的颜色

excel - 有没有办法将图像添加到 VBA 中的消息框?

vba - 用vba清理excel表

ms-access - MS Access vba 以编程方式 Access 和设置标签属性

Excel VBA - 在一定范围内插入多列

excel - VBA查找具有匹配功能的列号

Excel 从列中提取值和平均值

java - 程序停止尝试读取 Excel 工作簿 (Apache POI)