I cobbled together some JavaScript to label the last point of each series in a chart (see below). This is a simplified version of a much-used function in a VBA add-in.
I used let mychart = mysheet.charts.getItemAt(0);
to specify that the code should run on the first chart object on the worksheet. It would be more useful to run the code on the chart selected by the user.
- How do I identify which chart the user has selected (
ActiveChart
in VBA-speak)?
Similarly I used for (var iseries = 0; iseries < nseries; iseries++)
to run the code on all series in the chart. It would be more useful to run the code on the specific series selected by the user.
- How do I identify which series in the chart has been selected by the user (related to
TypeName(Selection)
in VBA)?
Here is my Office-JS code:
$("#run").click(() => tryCatch(labelLastPoint));
//$("#label-last-point").click(labelLastPoint);
async function labelLastPoint() {
await Excel.run(async (context) => {
let mysheet = context.workbook.worksheets.getActiveWorksheet();
let mychart = mysheet.charts.getItemAt(0);
let seriescollection = mychart.series;
seriescollection.load("count");
await context.sync();
console.log("Number of Series: " + seriescollection.count);
let nseries = seriescollection.count;
for (var iseries = 0; iseries < nseries; iseries++) {
console.log("- Series Number " + iseries);
let myseries = seriescollection.getItemAt(iseries);
let pointcollection = myseries.points;
pointcollection.load("count");
await context.sync();
let npoints = myseries.points.count;
let mypoint = myseries.points.getItemAt(npoints - 1);
mypoint.hasDataLabel = true;
mypoint.dataLabel.showSeriesName = true;
mypoint.dataLabel.showValue = false;
}
});
}