我有以下代码,我最近发现如果我的条件格式与范围不完全匹配,我会收到运行时错误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
在运行上述代码之前,运行以下命令以创建条件格式并将其优先级设置为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
下一步
如果我在运行通过vba创建条件格式的代码后创建了一个额外的条件格式,它可以正常工作,但是如果我在运行它之前创建了任何条件格式并且范围不是A1:GJH5000那么我得到错误1004.似乎成为我的vba索引创建格式更改的问题,因此它不是1.我的理解是Selection.FormatConditions(Selection.FormatConditions.count).SetFirstPriority
应该将新创建的条件设置为仅索引1,但它似乎是将它们全部设置为代替。奇怪的是,如果我有我的vba创建的条件格式和另一个用户定义的具有完全相同的范围,那么删除按预期工作,这使我认为优先级设置正确,所以可能导致用户定义错误,是否有解决方法?