首页 > 解决方案 > 如何将颜色格式化为图表数据标签的几个字符?

问题描述

我有一个饼图,其中包含类别和百分比作为数据标签。我只想要红色的类别名称而不是百分比。我希望这在 VBA 中完成。它在使用时工作font.bold

Sub ex()
    Dim Ch As ChartObject
    Set Ch = Sheet1.ChartObjects(1)
    Dim s As Series
    Set s = Ch.Chart.SeriesCollection(1)

    Dim p As Point
    Set p = s.Points(4)
    p.DataLabel.Format.TextFrame2.TextRange.Characters(1, 1).Font.Fill.ForeColor.RGB = rgbRed
End Sub

标签: excelvbacharts

解决方案


如果您的类别名称大小不同,您可能想尝试这样的事情?

Option Explicit

Sub Sample()
    Dim objChart As ChartObject
    Set objChart = Sheet1.ChartObjects(1)
    
    Dim Chrt As Chart
    Set Chrt = objChart.Chart
    
    Dim objSeries As Series
    Set objSeries = Chrt.SeriesCollection(1)

    Dim p As Point
    '~~> Change this to the releavant point
    Set p = objSeries.Points(3)
        
    Dim CatValueLength As Long
    
    With p.DataLabel.Format.TextFrame2.TextRange
       .InsertChartField msoChartFieldCategoryName, "", 1
       
       '~~> If separator is newline then change
       '    ", "    to     "" & Chr(10) & ""
       '~~> Or if it something else then change accordingly
       .InsertAfter ", "
       
       '~~> Get the category value, length so that we can insert % values
       CatValueLength = Len(p.DataLabel.Text)
       
       '~~> Include the percentage
       .InsertChartField msoChartFieldPercentage, "", CatValueLength
       
       '~~> Color the category name
       .Characters(1, CatValueLength).Font.Fill.ForeColor.RGB = rgbRed
    End With
End Sub

在行动

在此处输入图像描述


推荐阅读