I set some rules in VBA to conditionaly formating some cells of a Range. Here is a sample of my code :
Private Sub FormatRange()
Dim Rng01, Rng02 As Range,
listSep As String
Set Rng01 = Range("A14:O28")
listSep = Application.International(xlListSeparator)
Set Rng02 = Intersect(Rng01, Rng01.Parent.Range("H:K"))
Rng02.FormatConditions.Add Type:=xlExpression, formula1:="=IsAlphaNumeric(" & Rng01.Cells(1,8).Address(0,1) & ")"
Rng02.FormatConditions(1).Interior.Color = RGB(255,0,0)
End Sub
The cells H from K are merged together. if I'm using the Conditional formating option the merged cells with a non alphanumeric caractére turn red, as expected.
But I want to use VBA, and according to this preview post : VBA conditional formatting based on contents of merged cells I can't get the value using : Rng01.Cells(1,8).Address(0,1) because Cells(1,8) only target the column "H" and not "H/I/J/K"
Any solutions ?
CodePudding user response:
If my assumptions are correct, this might work for you:
Private Sub FormatRange()
Dim Rng01 As Range, Rng02 As Range, listSep As String
Set Rng01 = Range("A14:O28")
listSep = Application.International(xlListSeparator)
Set Rng02 = Intersect(Rng01, Rng01.Parent.Range("H:K"))
Dim fc As FormatCondition
Set fc = Rng02.FormatConditions.Add(Type:=xlExpression, Formula1:="=IsAlphaNumeric(" & Rng02.Cells(1, 1).MergeArea.Address(0, 1) & ")")
fc.Interior.Color = RGB(255, 0, 0)
End Sub
CodePudding user response:
Since you did not clarify my comment question, please try the next way. It assumes that you want conditional formatting all Rng01
range based on alpha numeric values in merged cells ("H:K"). All cells to have a red Interior
in such a case. If the code uses Rng01.Cells(1,8).Address(0,1)
it is enough, because a merged cells group exposed only its first cell:
Private Sub FormatRangeAlpha()
Dim Rng01 As Range, Rng02 As Range, listSep As String
Set Rng01 = Range("A14:O28")
listSep = Application.International(xlListSeparator)
Set Rng02 = Intersect(Rng01, Rng01.Parent.Range("H:K"))
With Rng01
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, formula1:="=NOT(ISNUMBER(" & .cells(1, 8).Address(0, 1) & "))"
.FormatConditions(1).Interior.Color = RGB(255, 0, 0)
End If
End Sub
CodePudding user response:
for some reasons It's working now without editing the code ... The only things I did was to unmerge my cells H:K and then merge them again. Now it's working for each row as expected.