【问题标题】:Conditionally Coloring a Graph in Excel有条件地在 Excel 中为图表着色
【发布时间】:2015-06-11 10:51:24
【问题描述】:

你好!

我正在尝试通过 VBA 在 Excel 中为图表(任务跟踪器)着色。这个想法是将所有“类别”着色为某种颜色 - 从视觉上看,这意味着将每个“行”上的所有条形都设置为特定颜色。我正在使用从http://peltiertech.com/vba-conditional-formatting-of-charts-by-category-label/复制的以下代码:

Sub ColorByCategoryLabel()
  Dim rPatterns As Range
  Dim iCategory As Long
  Dim vCategories As Variant
  Dim rCategory As Range

  Set rPatterns = ActiveSheet.Range("A1:A5")
  With ActiveChart.SeriesCollection(2)
    vCategories = .XValues
    For iCategory = 1 To UBound(vCategories)
      Set rCategory = rPatterns.Find(What:=vCategories(iCategory))
      .Points(iCategory).Format.Fill.ForeColor.RGB = rCategory.Interior.Color
    Next
  End With
End Sub

我不知道出了什么问题。

基本上,我有一个系列 (series2),水平(类别)轴标签由 1-5 的整数组成。这个类别决定了条的垂直位置,但我还想根据这个垂直位置,根据范围(a1:a5)中的颜色,为这个系列中的每个条着色——这正是这段代码的样子正在做。

关于代码的任何建议,或者可能是基于“水平(类别)轴”值的彩色条形图的任何替代方法?

谢谢!

【问题讨论】:

  • 此代码是否运行,但未产生所需的结果 - 还是抛出错误?如果是后者,哪一行?我注意到 Peltier 代码有两个变体,具体取决于您使用的 Excel 版本 - 您指的是正确的属性吗?
  • 嘿,马克,它运行了,但着色不正确。我终于通过了它,偶然发现了一些 VBA 以使其正常工作。感谢您的回复。
  • 请注意,在水平条形图中,类别轴是垂直轴。

标签: vba excel


【解决方案1】:

好吧,我通过逐步解决问题找到了答案。我无法想象这是根据高度绘制水平条形图的最简单方法,但它确实有效。

Sub ColorByCategoryLabel()
  Dim iCategory As Long
  Dim vCategories As Variant
  Dim rCategory As Range

  Dim CurColor As Double
  Dim CurColorIndex As Long
  Dim CurHeight As Double

  CurHeight = 0
  CurColorIndex = 1
  CurColor = ActiveSheet.Cells(CurColorIndex + 1, 10).Interior.Color
  ActiveSheet.ChartObjects("Chart 1").Select
  With ActiveChart.SeriesCollection(2)
    vCategories = .XValues
    For iCategory = 1 To UBound(vCategories)
        If .Points(iCategory).Top > CurHeight Then
            CurColorIndex = CurColorIndex + 1
            CurColor = ActiveSheet.Cells(CurColorIndex + 1, 10).Interior.Color
            CurHeight = .Points(iCategory).Top
        End If
      .Points(iCategory).Format.Fill.ForeColor.RGB = CurColor
    Next
  End With
End Sub

您需要修改该行

Curcolor = ActiveSheet.Cells(CurColorIndex+1,10).Interior.Color

正确指定要复制其背景颜色的单元格。

顺便说一句,如果有人对 timetracker 感兴趣,可以在这里托管:https://drive.google.com/file/d/0B85fvjQDbl3lUVpPNmdGT1VkWW8/view?usp=sharing

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2015-12-14
    • 2021-07-16
    • 2023-04-07
    • 2020-03-02
    • 1970-01-01
    相关资源
    最近更新 更多