VBA For Each循环出现Type mismatch错误,求原因及解决办法
解决VBA条件格式遍历的类型不匹配错误
你遇到的类型不匹配错误,根源在于ws.Cells.FormatConditions集合里的元素不只有FormatCondition类型。Excel的条件格式还包含UniqueValues、Top10、ColorScale这类特殊格式对象,它们的类型和普通FormatCondition不同,直接用FormatCondition类型的变量遍历就会触发类型不匹配。
下面是修正后的代码,同时解决了遍历删除时可能漏删的问题:
Sub ClearBottomBorderConditionalFormatting() Dim ws As Worksheet Dim cf As Variant Dim i As Long Set ws = ThisWorkbook.Sheets("Sheet1") ' 倒序遍历,避免删除元素后集合索引混乱导致漏删 For i = ws.Cells.FormatConditions.Count To 1 Step -1 Set cf = ws.Cells.FormatConditions(i) ' 仅处理支持Borders属性的普通条件格式 If TypeName(cf) = "FormatCondition" Then If cf.Borders(xlBottom).LineStyle <> xlNone Then cf.Delete End If End If Next i End Sub
关键说明
- 用
Variant类型变量接收集合元素,兼容所有条件格式类型 - 倒序遍历:删除条件格式后,集合内后续元素会向前移位,正向遍历会跳过部分元素,倒序则不会
- 通过
TypeName(cf)判断类型:只有普通FormatCondition对象才有Borders属性,特殊格式(如颜色刻度、数据条)没有该属性,直接访问会触发新的错误
内容的提问来源于stack exchange,提问作者susi33
相关产品推荐
相关产品推荐

