Search code examples
excelvba

VBA Type missmatch in For Each loop


My code gives my type missmatch.

I dont know why, beacuse cf is type FormatCondition

Sub ClearBottomBorderConditionalFormatting()
    Dim ws As Worksheet
    Dim cf As FormatCondition
    
    
    Set ws = ThisWorkbook.Sheets("Sheet1")
    
    
    For Each cf In ws.Cells.FormatConditions
        
        If cf.Borders(xlBottom).LineStyle <> xlNone Then
            
            cf.Delete
        End If
    Next cf
End Sub

Solution

    • Believe or not, the type of cf is UniqueValues instead of FormatCondition.
    Sub ClearBottomBorderConditionalFormatting()
        Dim ws As Worksheet
        Dim cf  As Variant ' UniqueValues
        Set ws = ThisWorkbook.Sheets("Sheet1")
        For Each cf In ws.Cells.FormatConditions
            Debug.Print TypeName(cf) ' validate data type
            If cf.Borders(xlBottom).LineStyle <> xlNone Then
                cf.Delete
            End If
        Next cf
    End Sub
    

    Microsoft documentation:

    UniqueValues object (Excel)