In VB.Net, I had the following code (FoundCells being a range of cells I find via a LinQ query on my sheet)
With wks
For Each cl In FoundCells
Dim Rw As Integer = cl.Start.Row
' Udate the Date column with new labels
.Cells(Rw + 0, 1).Value = "Val1"
.Cells(Rw + 1, 1).Value = "Val2"
.Cells(Rw + 2, 1).Value = "Val3"
.Cells(Rw + 3, 1).Value = "Val4"
Dim x As New ExcelAddress(Rw + 3 & ":" & Rw + 3)
With .ConditionalFormatting.AddExpression(x)
.Style.Fill.BackgroundColor.Color = Color.Yellow
.Formula = "AND(ISNUMBER(A" & Rw + 3 & "),A" & Rw + 3 & "<>A" & Rw + 2 & ")"
End With
' Add in Row above this row
.InsertRow(Rw, 1)
End With
What this code did was it applied the conditional formatting to technically:
ExcelAddress(Rw + 2 & ":" & Rw + 2)
Rather than
ExcelAddress(Rw + 3 & ":" & Rw + 3)
In other words, even though the conditional formatting was set BEFORE the addition of the new row, the formatting got attached to the rows AFTER the addition.
I hope this makes sense.... In other words:
1) I set conditional formatting on Row 4
2) I add in a new row starting at Row 1
3) The conditional formatting STILL STAYED AT ROW 4 - (Rather than moving down to row 5)
I'm pretty sure this has to do with my "With Wks" statement maybe not committing the change till the "End With"
With wks
For Each cl In FoundCells
Dim Rw As Integer = cl.Start.Row
' Udate the Date column with new labels
.Cells(Rw + 0, 1).Value = "Val1"
.Cells(Rw + 1, 1).Value = "Val2"
.Cells(Rw + 2, 1).Value = "Val3"
.Cells(Rw + 3, 1).Value = "Val4"
Dim x As New ExcelAddress(Rw + 3 & ":" & Rw + 3)
With .ConditionalFormatting.AddExpression(x)
.Style.Fill.BackgroundColor.Color = Color.Yellow
.Formula = "AND(ISNUMBER(A" & Rw + 3 & "),A" & Rw + 3 & "<>A" & Rw + 2 & ")"
End With
' Add in Row above this row
.InsertRow(Rw, 1)
End With
What this code did was it applied the conditional formatting to technically:
ExcelAddress(Rw + 2 & ":" & Rw + 2)
Rather than
ExcelAddress(Rw + 3 & ":" & Rw + 3)
In other words, even though the conditional formatting was set BEFORE the addition of the new row, the formatting got attached to the rows AFTER the addition.
I hope this makes sense.... In other words:
1) I set conditional formatting on Row 4
2) I add in a new row starting at Row 1
3) The conditional formatting STILL STAYED AT ROW 4 - (Rather than moving down to row 5)
I'm pretty sure this has to do with my "With Wks" statement maybe not committing the change till the "End With"