谁能告诉我下面的代码有什么问题?
它大部分时间都在工作,但有时它无法应用适当的颜色。例如,如果单元格 D112 中的 % 从 97% 变为 100%,则不会应用绿色,但在某些情况下会应用绿色。
基本上基于单元格 D112 的 % 值,我想对条形图应用不同的颜色。
If Range("D112") < 0.96 Then
ActiveSheet.ChartObjects("Chart 18").Activate
ActiveChart.FullSeriesCollection(1).Select
ActiveChart.FullSeriesCollection(1).Points(3).Select
With Selection.Format.Fill
.Visible = msoTrue
.ForeColor.RGB = RGB(204, 0, 51)
.Transparency = 0
.Solid
End With
Range("P8").Interior.Color = RGB(204, 0, 51)
ElseIf Range("D112") >= 0.96 And Range("D112") <= 0.98 Then
ActiveSheet.ChartObjects("Chart 18").Activate
ActiveChart.FullSeriesCollection(1).Select
ActiveChart.FullSeriesCollection(1).Points(3).Select
With Selection.Format.Fill
.Visible = msoTrue
.ForeColor.RGB = RGB(255, 102, 0)
.Transparency = 0
.Solid
End With
Range("P8").Interior.Color = RGB(255, 102, 0)
Else
ActiveSheet.ChartObjects("Chart 18").Activate
ActiveChart.FullSeriesCollection(1).Select
ActiveChart.FullSeriesCollection(1).Points(3).Select
With Selection.Format.Fill
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 153, 102)
.Transparency = 0
.Solid
End With
Range("P8").Interior.Color = RGB(0, 153, 102)
End If
首先:你可以用Select Case
替换你多个If
和Else
,它会清理和缩短你的代码很多。
第二:无需在每个条件中选择图表和点,您对所有场景重复相同的过程,您可以在If
s部分(或Select Case
(之前执行此操作。
第三:最好避免使用Select
、Activate
和Selection
,而是完全限定所有图表、系列和点对象。
下面的代码中有更多解释;
法典
Option Explicit
Sub ColorGraphs()
Dim ChrtObj As ChartObject
Dim Ser As Series
Dim SerPoint As Point
' set the ChartObject
Set ChrtObj = ActiveSheet.ChartObjects("Chart 18")
' set the Series
Set Ser = ChrtObj.Chart.SeriesCollection(1)
' set the series point
Set SerPoint = Ser.Points(3)
' these setting are the same for all your scenarios
With SerPoint.Format.Fill
.Visible = msoTrue
.Transparency = 0
.Solid
End With
Select Case Range("D112").Value
Case Is < 0.96
SerPoint.Format.Fill.ForeColor.RGB = RGB(204, 0, 51)
Range("P8").Interior.Color = RGB(204, 0, 51)
Case 0.96 To 0.98
SerPoint.Format.Fill.ForeColor.RGB = RGB(255, 102, 0)
Range("P8").Interior.Color = RGB(255, 102, 0)
Case Else ' larger than 0.98
SerPoint.Format.Fill.ForeColor.RGB = RGB(0, 153, 102)
Range("P8").Interior.Color = RGB(0, 153, 102)
End Select
End Sub