Trying to write a macro that deletes all but the first and last N conditional formats.
Excel 2007 has a bug that generates tons of spurious copies of the (desired, user-generated conditional formatting as you copy-paste ranges. I can delete all at once easily enough, but then I have to recreate each desired conditional format. Or I can manually delete the spurious ones through the Excel toolbar interface, but I have to choose and confirm each single deletion, and these can number in the hundreds, thanks to this bug.
So, here's my code:
Sub DeleteAllButXConditionalFormats()
On Error GoTo ErrHandler
' There seems to be a bug: type FormatConditions is not recognized as a collection of FormatCondition objects.
'Dim cond As Variant
Dim cond As FormatCondition
Dim i As Long
Dim lngX As Long
lngX = InputBox( _
"How many of the first and last conditional formats should be retained on this page? All others will be deleted. Enter 0, or click Cancel, to leave the conditional formats intact.", _
"Delete All But X Conditional Formats")
i = 0
If (lngX > 0) Then
With ActiveSheet.Cells
For Each cond In .FormatConditions
i = i + 1
If (i > lngX) And (i <= ActiveSheet.Cells.FormatConditions.Count - lngX) Then
cond.Delete
End If
Next cond
End With
End If
GoTo LocalExit
ErrHandler:
MsgBox Err.Source & " generated this error description: " _
& vbNewLine & vbNewLine & Err.Description, , _
"Debug Error In My Macro", Err.HelpFile, Err.HelpContext
Stop: Resume
LocalExit:
End Sub
1. You'd think that setting cond as type FormatCondition would make it a member of type FormatConditions, but then the line
For Each cond In .FormatConditions
produces a "Type mismatch" error. So, I changed it to Variant.
2. As type Variant, it produces an error on the line
"Application-defined or object-defined error".
3. So, I tried using a simple counter:
With ActiveSheet.Cells
For i = .FormatConditions.Count - lngX To lngX + 1 Step -1
.FormatConditions(i).Delete
Next i
End With
Same "Application-defined or object-defined error".
OK, there's obviously some bugs in MS Excel's application model (unless I'm missing an obvious mistake or three). Anyone know a workaround?
Bookmarks