Sub AddFormatCondition()
Dim Rng As Range, MyRange(1 To 3) As Range
Dim Appear(1 To 3) As Variant, Values(1 To 3) As Variant
Dim App(1 To 3) As Variant, Val(1 To 3) As Variant
Dim RngVal As String
Set MyRange(1) = Range("B9:B31")
Set MyRange(2) = Range("C9:C31")
Set MyRange(3) = Range("D9:D31")
Appear(1) = "Apple,Orange"
Appear(2) = "Red,Blue,Purple,Yellow,Green"
Appear(3) = "Open,Close"
Val(1) = "1,2"
'Val(2) = "A,B,C,D,E" ' FormatConditions not work with Text
Val(2) = "1,2,3,4,5" ' So convert to Numbers
'Val(3) = "I,II" ' FormatConditions not work with Text
Val(3) = "1,2" ' So convert to Numbers
Range("A1:A2") = Application.Transpose(Split("1,2", ","))
Range("B1:B2") = Application.Transpose(Split("Apple,Orange", ","))
Range("D1:D5") = Application.Transpose(Split("1,2,3,4,5", ","))
Range("E1:E5") = Application.Transpose(Split("Red,Blue,purple,Yellow,Green", ","))
Range("G1:G2") = Application.Transpose(Split("1,2", ","))
Range("H1:H2") = Application.Transpose(Split("Open,Close", ","))
Range("A9:A21") = Application.Transpose(Split("Jone,Ann,Tom,Susan,Rebert,Jade,Sue,Helen,Jeffery,Joey,Dicky,Suki,Jimmy", ","))
Range("B9:B21") = Application.Transpose(Split("2,1,1,2,2,2,1,1,1,2,2,1,2", ","))
'Range("C9:C21") = Application.Transpose(Split("B,A,A,C,C,E,E,A,C,D,C,C,A", ","))' FormatConditions not work with Text
Range("C9:C21") = Application.Transpose(Split("2,1,1,3,3,5,5,1,3,4,3,3,1", ",")) ' So convert to Numbers
'Range("D9:D21") = Application.Transpose(Split("I,II,I,I,I,II,I,I,I,II,II,II,I", ","))' FormatConditions not work with Text
Range("D9:D21") = Application.Transpose(Split("1,2,1,1,1,2,1,1,1,2,2,2,1", ",")) ' So convert to Numbers
For I = 1 To 3
For Each Rng In MyRange(I)
With Rng
.FormatConditions.Delete
App(I) = Split(Appear(I), ",")
For c = LBound(App(I)) To UBound(App(I))
RngVal = Split(Val(I), ",")(c)
If IsNumeric(RngVal) = True Then
.FormatConditions.Add Type:=xlExpression, Formula1:="=" & Rng.Address & "=" & RngVal & ""
Else
RngVal = """" & RngVal & """"
.FormatConditions.Add Type:=xlExpression, Formula1:="=" & Rng.Address & "=" & RngVal & ""
End If
.FormatConditions(.FormatConditions.Count).SetFirstPriority
.FormatConditions(1).StopIfTrue = False
.FormatConditions(1).NumberFormat = """" & App(I)(c) & """"
Next
End With
Next
Next
Range("B9").Activate' see what contain
End Sub