【问题标题】:Excel - Conditionally format .DataLabel property on chart based on value in data tableExcel - 根据数据表中的值有条件地格式化图表上的 .DataLabel 属性
【发布时间】:2020-03-27 15:54:36
【问题描述】:

我尝试使用 VBA 和添加多个数据系列来做到这一点,但我认为由于我的图表类型,我必须使用 VBA。我正在使用这个模板:https://templates.office.com/en-au/project-timeline-with-milestones-tm00000009。在数据表上,我添加了一个附加列“类别”,其中包含特定“里程碑”所属的五个不同类别之一。我已将图表上的数据标签格式化为在其后面添加填充颜色,并且我希望能够根据里程碑所在的类别更改该颜色。

非常感谢任何帮助!

【问题讨论】:

标签: excel vba object charts formatting


【解决方案1】:

检查此代码的 cmets 并对其进行自定义以满足您的需求

将它放在保存图表的表格后面:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    ' Declare object variables
    Dim evalTable As ListObject

    ' Declare other variables
    Dim sheetName As String
    Dim tableName As String
    Dim categoryColumnNumber As Long
    Dim chartPointNum As Long

    ' Customize to fit your needs
    sheetName = "Project Timeline"
    tableName = "ProjectDetails"
    categoryColumnNumber = 6

    ' Initialize table that holds chart data
    Set evalTable = ThisWorkbook.Sheets(sheetName).ListObjects(tableName)

    ' Check if current cell changed belongs to column where categories are defined
    If Not Intersect(Target, evalTable.DataBodyRange.Columns(categoryColumnNumber)) Is Nothing Then

        ' Get the data label number based on cell's position among table
        chartPointNum = Target.Row - evalTable.HeaderRowRange.Row

        ' Set data label background color based on changed cell and it's position
        SetDataLabelColor Target, chartPointNum

    End If

End Sub


Public Sub SetDataLabelColor(TargetCell As Range, chartPointNum As Long)

    Dim evalChart As ChartObject

    Set evalChart = ActiveSheet.ChartObjects("Project Timeline")

    With evalChart.Chart.FullSeriesCollection(2).Points(chartPointNum).DataLabel.Format.Fill
        .Visible = msoTrue
        ' Credits: https://stackoverflow.com/a/28058868/1521579
        .ForeColor.RGB = RGB((TargetCell.Interior.Color Mod 256), ((TargetCell.Interior.Color \ 256) Mod 256), (TargetCell.Interior.Color \ 65536))
        .Transparency = 0
        .Solid
    End With
End Sub

如果有帮助,记得标记答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2014-04-27
    • 2020-05-23
    • 2022-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多