标签:VBA
这是在vbaexpress.com上看到的一个示例,相对较简单,但是运用了数组及一些VBA语句,初学者可以参考。
如下图1所示,在名为“Test_Data”的工作表中,我想查找A列中的“Apple”“Banana”,同时B列中对应为“SS”或“PP”,将满足这两个条件的行设置红色背景。
图1
打开VBE,插入一个标准模块,输入下面的代码:
代码语言:javascript复制Sub Set_Patterns()
Dim i As Long
Dim d As Range
Dim Source As Worksheet
Dim fruit As Variant
Dim rSS As Range
Dim rPP As Range
Set Source = ActiveWorkbook.Worksheets("Test_Data")
fruit = Array("Apple", "Banana", "Cherry")
For i = LBound(fruit) To UBound(fruit)
Set rSS = Nothing
Set rPP = Nothing
For Each d In Source.Range("A2:A10").Cells
If d = fruit(i) Then
Select Case d.Offset(0, 1)
Case "SS"
Set rSS = d
Case "PP"
Set rPP = d
End Select
End If
Next d
If Not (rPP Is Nothing Or rSS Is Nothing) Then
rPP.Resize(1, 2).Interior.Color = vbRed
rSS.Resize(1, 2).Interior.Color = vbRed
End If
Next i
End Sub
代码很简单,对于初学者来说是一个很好的练手示例,有兴趣的朋友可以试试。