PDA

View Full Version : [SOLVED:] VBA Celloffset function in For Each Cell function not work



Junji Qian
01-20-2017, 03:06 PM
Hi,
Can someone help me check the below code? The first sub works, it changes the interior color of duplicate cells in selection.
However, the second one not work because of the if function.
The offset and interior condition both not work.

Thank you!
---------------------------------------------------------------------------------------------------

Sub dup()
' dup Macro
Selection.FormatConditions.AddUniqueValues
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriori ty
Selection.FormatConditions(1).DupeUnique = xlDuplicate
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Call Bold
End Sub

'wrong one but right intention

Sub Bold()
For Each cell In Selection
If cell.Interior.ColorIndex = 255 Then
cell.Offset(-4, 0).Font.Bold = True
End If
Next cell
End Sub

SamT
01-20-2017, 05:03 PM
FormatCondition does not effect the Interior of Ranges. IOW, the Cells Interior Colors and ColorIndexes have not been set.

ColorIndexes can only be 1 to 56 and a couple of constants that mean no color.
Colors can be any of a few vbConstants or any RGB color code

p45cal
01-21-2017, 03:44 AM
Sub dup()
' dup Macro
Selection.FormatConditions.AddUniqueValues
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriori ty
Selection.FormatConditions(1).DupeUnique = xlDuplicate
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Call Bold
End Sub
Sub Bold()
For Each cell In Selection
If cell.DisplayFormat.Interior.Color = 255 Then
cell.Offset(-4, 0).Font.Bold = True
End If
Next cell
End Sub
Realise that
cell.Offset(-4, 0).Font.Bold = True
boldens the cell 4 cells ABOVE the selection.
The only changes are:
If cell.DisplayFormat.Interior.Color = 255 Then

Junji Qian
01-23-2017, 03:14 PM
Thank you SamT for the suggestions. I was confused by the colorindex before but now I understand.
Thanks!

Junji Qian
01-23-2017, 03:15 PM
Thank you so much P45cal!!! Your code works perfectly. I can appreciate anymore :)