AI, Excel VBA and Office Scripts

Excel can record macros. Recorded macros have lots of limitations. Custom written VBA macros have few limitations. AI can help you create custom written macros without having to record them. AI can also write Office scripts to automate processes.

I was looking at an old blog post – link below.
https://a4accounting.com.au/excel-chart-label-line-break/

I thought a macro could make adding and tweaking the labels easier.
When creating a stacked bar or column chart, tweaking the labels is a manual process. You can add labels in one click but modifying them requires separately changing each label. That’s where automation comes in.

VBA macro

I asked Copilot (Microsoft’s AI platform) to write a VBA macro that amends the active chart and adds the data labels for Series Name and Value plus insert a line break between them. Here is the macro created by Copilot.

Sub AddSeriesNameAndValueLabels()
'AI - 12/10/2025
'inserts data labels with a line break in active chart
Dim s As Series

If ActiveChart Is Nothing Then
MsgBox "Please select a chart first.", vbExclamation
Exit Sub
End If

For Each s In ActiveChart.SeriesCollection
s.ApplyDataLabels
With s.DataLabels
.ShowSeriesName = True
.ShowValue = True
.Separator = vbLf
End With
Next s


If you are new to macros see the post below about using macro code.
https://a4accounting.com.au/how-to-make-the-most-of-excel-macros/

Office script

I also asked Copilot to create an Office script to do the same. See below.

function main(workbook: ExcelScript.Workbook) {
const chart = workbook.getActiveChart();
if (!chart) {
    throw new Error("Please select a chart before running the script.");
}

chart.getSeries().forEach((series) => {
    const labels = series.getDataLabels();

    labels.setShowSeriesName(true);
    labels.setShowValue(true);
    labels.setSeparator("\n");
});

}

In both cases the code will display an error if a chart isn’t selected when the code is run.
VBA displays a message box.

The Office script displays a message in the Task Pane on the right of screen.

My next post will cover the basics of using Office scripts.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.