Excel:错误1004时尝试range.conditionalformat(1).delete?

我有下面的代码,我最近发现,如果我有条件格式不完全匹配范围,我得到运行时错误1004-用户定义或对象定义的错误。

For Each ws In ThisWorkbook.Worksheets If Not (ws.Name = "Instructions (protected)" Or ws.Name = "ReplacementMacro (protected)" Or ws.Name = "Line Pay Finder (protected)" Or ws.Name = "Line Inserter (protected)" Or ws.Name = "Symbol Inserter (protected)" Or ws.Name = "Configuration Data (protected)") And ws.ProtectContents = False Then ws.Activate Dim myRange As Range Set myRange = Range("A1:GJH5000") myRange.FormatConditions(1).Delete End If Next ws 

在上面的代码运行之前,运行以下代码创build一个条件格式并将其优先级设置为1。

 For Each ws In ThisWorkbook.Worksheets If Not (ws.Name = "Instructions (protected)" Or ws.Name = "ReplacementMacro (protected)" Or ws.Name = "Line Pay Finder (protected)" Or ws.Name = "Line Inserter (protected)" Or ws.Name = "Symbol Inserter (protected)" Or ws.Name = "Configuration Data (protected)") And ws.ProtectContents = False Then ws.Activate Dim myRange As Range Set myRange = Range("A1:GJH5000") Range("A1").Activate myRange.FormatConditions.Add Type:=xlExpression, Formula1:= _ "=AND(viewBoxEnabled=TRUE, OR(CELL(""col"")- viewBoxLeft >CELL(""col"",A1), CELL(""col"")+ viewBoxRight<CELL(""col"",A1), CELL(""row"")- viewBoxAbove >CELL(""row"",A1), CELL(""row"")+ viewBoxBelow <CELL(""row"",A1)))" myRange.FormatConditions(Selection.FormatConditions.count).SetFirstPriority With myRange.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent1 .TintAndShade = 0 End With myRange.FormatConditions(1).StopIfTrue = False End If 

下一个ws

如果我创build一个额外的条件格式后,运行通过vba创build条件格式的代码,它工作正常,但如果我创build任何之前运行它,范围不是A1:GJH5000那么我得到错误1004。它似乎是问题与我创build的格式的索引改变,所以它不是1.我的理解是Selection.FormatConditions(Selection.FormatConditions.count).SetFirstPriority应该设置新创build的条件只索引1,但它似乎将它们全部设置。 奇怪的是,如果我有我的VBA创build的条件格式和另一个用户定义一个具有完全相同的范围,然后删除按预期工作,使我认为优先级设置正确,所以可能导致用户定义错误,是否有工作?

示例工作簿