我对 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/