根据单元格值更改条形颜色

时间:2018-06-25 19:55:28

标签: google-apps-script google-sheets google-visualization

我正在尝试寻找一种解决方案,以根据单元格的值或颜色自动调整图表中堆积条形的颜色。

具体来说,当我更改F2的值时,我希望条也根据单元格的颜色或单元格的值/字符串更改颜色。

这是我的工作表:https://docs.google.com/spreadsheets/d/1QwAVPEtQ3l7iIZhLDYMT1I9eGc7HoaFsTyg1p-hi3G8/edit?usp=sharing

我已经设置了我的测试数据和研究过的解决方案,但是还没有找到一种方法可以完全满足我的需求。

我希望找到一个解决方案,并且我倾向于Apps脚本方法,因为在“条件格式”菜单中看不到任何可控制图表系列格式的选项,并且我也没有看到条形图菜单中的任何选项都可以定位到特定的单元格。

任何建议或指导都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以基于对工作表的修改来修改图表。

使用简单的触发函数onEdit及其事件对象,您可以确定是否进行了更改参考单元格的图纸编辑。如果进行了编辑,则可以访问工作表的嵌入式图表,并根据需要对其进行修改:

function onEdit(e) {
  if (!e) throw new Error("You ran this manually");
  const sheet = e.range.getSheet();

  // Sanity check: only care about edits on the desired sheet.
  if (sheet.getName() !== "some sheet name with your reference cell on it")
    return;
  // Sanity check: only care about edits to the reference cell:
  if (e.range.getA1Notation() !== "reference cell A1 notation here")
    return;
  // Sanity check: only care if there is a new value.
  if (e.value === undefined)
    return;
  // Example change: alter the color of the 3rd series. Assumption: e.value is a
  // valid CSS color or CSS color code. If it is numeric, write code to transform it.
  modifyChart_(sheet, 2, e.value)
}

function modifyChart_(sheet, seriesIndex, newCssColor) {
  // Assume there is only one chart on this sheet.
  const charts = sheet.getCharts();
  if (charts.length > 1)
    console.warn("Assumption invalid: more than 1 chart on the given sheet");
  const barBuilder = charts[0].modify().asBarChart();

  const option = {};
  option[seriesIndex] = {"color": newCssColor};
  barBuilder.setOption("series", option);

  // Update the chart on the sheet.
  sheet.updateChart(barBuilder.build());
}

参考文档(又名必读):