简体   繁体   English

Excel 2007 VBA中重叠范围的条件格式-错误?

[英]Conditional formatting of overlapping ranges in Excel 2007 VBA - bug?

Currently trying to help on this question - but stumbled across a very strange problem: 目前正在尝试帮助解决这个问题 -但偶然发现了一个非常奇怪的问题:

When trying to add conditional formatting on overlapping ranges (in VBA), Excel 2007 produces Error 1004 or or Error 9 (Subscript out of range) errors. 尝试在重叠范围(在VBA中)上添加条件格式时,Excel 2007会产生错误1004或错误9(下标超出范围)错误。 I managed to boil the erroneous code down to this: 我设法将错误代码简化为:

Sub Produce1004()
    Cells.FormatConditions.Delete
    Range("A1").FormatConditions.Add Type:=xlExpression, Formula1:="=1"
    Range("A1:A2").FormatConditions.Add Type:=xlExpression, Formula1:="=1"
    Range("A1:A2").FormatConditions(Range("A1:A2").FormatConditions.Count).Font.ColorIndex = 7
End Sub

Sub ProduceError9()
    Cells.FormatConditions.Delete
    Range("A1:A3").FormatConditions.Add Type:=2, Formula1:="=1"
    Range("A1:A2").FormatConditions.Add Type:=2, Formula1:="=1"
    Range("A1:A2").FormatConditions.Add Type:=2, Formula1:="=1"
    Range("A1:A2").FormatConditions(Range("A1:A2").FormatConditions.Count).Font.ColorIndex = 3
End Sub

It's the last line in both subs that causes the error. 这是两个子句中的最后一行导致错误。 The error only occurs in Excel 2007, it runs fine in 2010. 该错误仅在Excel 2007中发生,在2010年运行良好。

Does anybody know a workaround? 有人知道解决方法吗?

I can see a problem in Produce1004() : 我可以在Produce1004()中看到一个问题:

A1 has 2 format conditions and A2 has 1 format condition. A1有2种格式条件,而A2有1种格式条件。

Range("A1:A2").FormatConditions.Count gives the count for A1, FormatConditions(2) doesn't exist for A2, hence the error. Range(“ A1:A2”)。FormatConditions.Count给出A1的计数,而FormatConditions(2)对于A2不存在,因此发生错误。

But for ProduceError9() the number of format conditions is the same for A1 and A2. 但是对于ProduceError9(),格式条件的数量对于A1和A2是相同的。

With a little experimentation, I can explain this by deducing that the range is stored with the format condition (setting the font for [A1].FormatCondition(3) also fails). 通过一点试验,我可以通过推断范围是与格式条件一起存储(为[A1] .FormatCondition(3)设置字体也失败)来解释这一点。 One must change the format for the range for which the format condition was defined. 必须为定义格式条件的范围更改格式。

Presumably, Excel 2010 improves on this situation by splitting a format condition on the fly. 据推测,Excel 2010通过动态拆分格式条件来改善了这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM