根据当前记录的值与上一个记录相比,更改标签的颜色

时间:2018-07-30 20:44:02

标签: vba excel-vba

尝试找到一种方法,当记录的值大于或小于前一个记录的值时,自动更改图表中标签的颜色(如果变高则变为绿色,如果变少则变为红色)。
如果要比较的值是硬连线的,我有一个代码可以工作,但是我需要一个动态选项。

请在下面找到我要在当前代码中解决的问题:
1.将标签值与上一个值进行比较(第一个值与0进行比较,如果为零,则为黑色,否则为红色)
2.将颜色更改为红色(255,0,0)和绿色(0,176,80)-当前使用主题颜色(不知道如何使用RGB代码)

Sub LabelFontColor()
Dim ser As Series
Dim ser_vals As Variant
Dim num As Integer

Set ser = ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1)
ser_vals = ser.Values

For num = LBound(ser_vals) To UBound(ser_vals)
    With ser.Points(num).DataLabel.Format.TextFrame2.TextRange.Font.Fill.ForeColor
        If ser_vals(num) > 0.15 Then 'tried ser_vals(num-1) but it didn't work
            .ObjectThemeColor = msoThemeColorAccent2
        Else
            .ObjectThemeColor = msoThemeColorAccent3
        End If
    End With
Next num
End Sub

2 个答案:

答案 0 :(得分:1)

看起来您在正确的-1位置上,但是它可能在第一行中失败了,请尝试如下操作:

Sub LabelFontColor()
    Dim ser As Series
    Dim ser_vals As Variant
    Dim num As Integer

    Set ser = ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1)
    ser_vals = ser.Values

    For num = LBound(ser_vals) To UBound(ser_vals)
        With ser.Points(num).DataLabel.Format.TextFrame2.TextRange.Font.Fill.ForeColor
            If num > LBound(ser_vals) Then
                If ser_vals(num) > ser_vals(num - 1) Then
                    .ObjectThemeColor = msoThemeColorAccent2
                Else
                    .ObjectThemeColor = msoThemeColorAccent3
                End If
            Else
                .ObjectThemeColor = msoThemeColorAccent3
            End If
        End With
    Next num
End Sub

答案 1 :(得分:1)

不能做“-1”的原因是第一个比较没有比这低的了。您需要一个单独的变量来跟踪最后一个值。

我还添加了您想要的RGB颜色代码:

Public Sub LabelFontColor()
    Dim ser As Series
    Dim ser_vals As Variant
    Dim num As Integer
    Dim previousVal As Variant

    Set ser = ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1)
    ser_vals = ser.Values
    previousVal = 0

    For num = LBound(ser_vals) To UBound(ser_vals)
        With ser.Points(num).DataLabel.Format.TextFrame2.TextRange.Font.Fill.ForeColor
            If ser_vals(num) > previousVal Then  'tried ser_vals(num-1) but it didn't work
                .RGB = RGB(0, 176, 80)
            Else
                .RGB = RGB(255, 0, 0)
            End If
        End With

        previousVal = ser_vals(num)
    Next num
End Sub