【问题标题】:VBA - Conditional formatting: Excel 2010 won't work, Excel 2013 willVBA - 条件格式:Excel 2010 将不起作用,Excel 2013 将
【发布时间】:2014-10-22 13:50:01
【问题描述】:

我最近写了一段代码,它检测(但不选择)Range,它必须是条件格式,然后调用一个完成这项工作的子例程。

' Format
For Each ws In Results.Sheets
    Format_em_all ws.Range(ws.Cells(15, 2), ws.Cells(15 + UBound(FreqToCompare), WrittenCells))
Next ws

其中ws 声明为WorksheetResults 声明为WorkbookFreqToCompare 是一个不可能为空的数组,WrittenCells 是一个不等于 0 的整数。

调用的子程序:

Sub Format_em_all(RangeToFormat As Range)

    Select Case RangeToFormat.Parent.Name

    Case "lol"
        RangeToFormat.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:="=2.9"
        RangeToFormat.FormatConditions(1).Interior.ColorIndex = 3
        RangeToFormat.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, Formula1:="=2.00001", Formula2:="=2.9"
        RangeToFormat.FormatConditions(2).Font.ColorIndex = 3

    Case "rofl"
        RangeToFormat.FormatConditions.Add Type:=xlCellValue, Operator:=xlNotBetween, Formula1:="=-4", Formula2:="=4"
        RangeToFormat.FormatConditions(1).Interior.ColorIndex = 3

    End Select

End Sub

我在计算机上使用 Excel 2013 执行了代码,一切顺利。 10 分钟前,一位同事说我的宏不起作用……我们一起用 Excel 2010 检查他的电脑……是的,它不起作用。它卡在Case "lol" 之后的第一行,出现“运行时错误“5”-无效的过程调用或参数”。 我尝试? RangeToFormat.Address,它显示了正确的范围地址...有什么问题?

【问题讨论】:

  • 你得到的错误是什么?是您期望的“神奇数字”吗(例如 xlCellValue=1)吗?
  • 此范围内是否已有条件格式?
  • “卡住”是什么意思?请通过对错误的描述进行澄清,或者(如果没有错误)详细说明观察到的结果与您的预期有何不同。
  • 添加了错误描述。 Excel 2013 在处理条件格式方面是否与 Excel 2010 不同,应该已经存在吗?其实没有,打开时文件是空白的,在调用这个子程序之前没有条件格式。
  • 我怀疑问题不在于 Excel 2010 与 2013,而是不同的小数分隔符。公式的类型是变体。因此,请尝试将公式设置为值而不是字符串。示例:RangeToFormat.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:=2.9RangeToFormat.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, Formula1:=2.00001, Formula2:=2.9

标签: vba excel excel-2010 excel-2013


【解决方案1】:

这个答案的功劳归于 Axel Richter:

Sub Format_em_all(RangeToFormat As Range)

Select Case RangeToFormat.Parent.Name

Case "lol"
    RangeToFormat.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:=2.9
    RangeToFormat.FormatConditions(1).Interior.ColorIndex = 3
    RangeToFormat.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, Formula1:=2.00001, Formula2:=2.9
    RangeToFormat.FormatConditions(2).Font.ColorIndex = 3

Case "rofl"
    RangeToFormat.FormatConditions.Add Type:=xlCellValue, Operator:=xlNotBetween, Formula1:=-4, Formula2:=4
    RangeToFormat.FormatConditions(1).Interior.ColorIndex = 3

End Select

End Sub

如您所见,公式不再是公式,而是整数!完美无缺

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多