addChart not working how "Record Actions" recorded it - office-scripts

I used the "Record Actions" in the Automate tab to record myself creating a chart. The Chart looks exactly how I want it to look after recording.
function main(workbook: ExcelScript.Workbook) {
let selectedSheet = workbook.getActiveWorksheet();
// Insert chart on sheet selectedSheet
let chart_24 = selectedSheet.addChart(ExcelScript.ChartType.pie, selectedSheet.getRange("A6:B7"));
}
I changed up the code a little bit so it could work when I call this Script from Power Automate.
function main(workbook: ExcelScript.Workbook) {
let sheet = workbook.getWorksheet("Dashboard");
let rng = sheet.getRange("A6:B7");
let chart_10 = sheet.addChart(ExcelScript.ChartType.pie, rng);
}
However, when I run either code above without having the data selected on the sheet, it is now giving me a bad chart like below.
This just started happening to me. I had the code working fine for me for about two months but now it is giving me the bad graph.
After testing the code, I noticed it only works when you have the data selected and the sheet open. When you run it in Power Automate ( where you can't use select() ) it will always give me the bad graph now. Ever since March 25, 2021, I have been getting the bad graph. Prior to this date, my code ran perfectly fine. How can I use a range without having to use select() so I can run it in Power Automate?

This is because the row and column used by pie chart are wrongly switched. You can try to click the "Switch Row/Column" button under "Chart" tab when selecting the chart to see the result.
As a workaround for Power Automate, you can use
function main(workbook: ExcelScript.Workbook) {
let sheet = workbook.getWorksheet("Sheet2");
let rng = sheet.getRange("A1:B2");
// 3rd parameter will help avoid this bug.
let chart_10 = sheet.addChart(ExcelScript.ChartType.pie, rng, ExcelScript.ChartSeriesBy.columns);
}

Related

Excel typescript update chart data series

I have created an office script that does some operations on excel data and creates a table. The data of this table is the input for a chart. The chart is already existing in the Excel file.
Now I need to update the data range of the chart manually whenever new items are added to the table, but I want to do this automated ofcourse.
I was not able to find any documentation on this. In VBA I can update data ranges of a chart and I tried to port that to the office script, but with no luck.
in VBA it is like this:
ActiveChart.FullSeriesCollection(1).XValues = "='summary and graph'!$A$2:$A$42"
ActiveChart.FullSeriesCollection(1).Values = "='summary and graph'!$B$2:$B$42"
ActiveChart.FullSeriesCollection(2).Values = "='summary and graph'!$C$2:$C$42"
What would be a way to do this in excel office script? What would the syntax be?
Thanks, Joris
Here is the code you get when you do the recording to create a chart for the table
function main(workbook: ExcelScript.Workbook) {
let selectedSheet = workbook.getActiveWorksheet();
let table1 = workbook.getTable("Table1");
// Insert chart on sheet selectedSheet with source data from table1
let chart_5 = selectedSheet.addChart(ExcelScript.ChartType.columnClustered, table1.getRange());
}
You can change the chart source data using the setData method.
You can also get the chart series collection using the getSeries method, and set Values for each series using the setValues method. Example code could be -
let seriesCollection = chart_5.getSeries();
let range = workbook.getWorksheet("summary and graph").getRange("B2:B42");
seriesCollection[0].setValues(range);
range = workbook.getWorksheet("summary and graph").getRange("C2:C42");
seriesCollection[1].setValues(range);

How to update the source data range for existing chart

I'm trying to write a script that finds data in a sheet dynamically (the dimensions of the table need to be flexible in both axis) and then updates the source data range for an existing chart on another sheet (so that my users don't need to set up the styling themselves).
Below is my script so far. Everything works apart from the final line where Excel Online gives me the error:
"Line 10: Chart setData: You cannot perform the requested operation"
function main(workbook: ExcelScript.Workbook)
{
let selectedSheet = workbook.getWorksheet("Enter data in this sheet");
// Add a new table at used range on selectedSheet
let range = selectedSheet.getUsedRange();
if(selectedSheet.getTables().length == 0)
{
let newTable = workbook.addTable(range, true);
}
workbook.getWorksheet("The Chart").getChart("Chart 1").setData(range);
}
The worksheet names are correct and so is the chart name as far as I can see:
screenshot of excel online showing chart and worksheet names
Answer found; the chart was on a protected sheet which did not allow editing of objects. Updating the protection to allow all users to edit objects has resolved the issue.

How to Clear Table Style in Office Scripts?

How can I clear the styles on a table? I tried recording the macro but when I record it and run it, it will say failed (Table setPredefinedTableStyle: The argument is invalid or missing or has an incorrect format.).
function main(workbook: ExcelScript.Workbook) {
let selectedSheet = workbook.getActiveWorksheet();
let mainTable = selectedSheet.getTable("MainTable");
mainTable.setPredefinedTableStyle("undefined");
}
How can I clear the table style?
https://learn.microsoft.com/en-us/javascript/api/office-scripts/excelscript/excelscript.table?view=office-scripts#setpredefinedtablestyle-predefinedtablestyle-
Excel tables in web always has a style. There isn't a way to clear all styles.
There doesn't appear to be a way to assign the "none" style, which is the most basic style. I'll follow-up on that.
The closest I can get to was to use TableStyleLight1 style as shown below.
function main(workbook: ExcelScript.Workbook) {
let selectedSheet = workbook.getActiveWorksheet();
let mainTable = selectedSheet.getTable("MainTable");
mainTable.setPredefinedTableStyle('TableStyleLight1')
}

Protect Worksheet in Office Scripts with Options

How can I protect a worksheet but allow the user to format the columns in Office Scripts? I have tried a few things but haven't had any success.
function main(workbook: ExcelScript.Workbook) {
let sheet = workbook.getWorksheet("By Item");
sheet.getProtection().protect(ExcelScript.WorksheetProtectionOptions.allowFormatColumns);
}
Please see the attached link
https://learn.microsoft.com/en-us/javascript/api/office-scripts/excelscript/excelscript.worksheetprotection?view=office-scripts#protect-options--password-
The protect() method takes an object as argument for the 1st argument. See below.
I noticed that cell background/fill doesn't work even with this setting. All other formatting works such as font color, border, etc. That may be a bug that we'll follow-up on.
function main(workbook: ExcelScript.Workbook) {
let sheet = workbook.getWorksheet("By Item");
sheet.getProtection().unprotect();
sheet.getProtection().protect({
allowFormatCells: true
});
}

How to handle event on data change in excel sheet to refresh all pivot tables?

I have a VBA code applied to Worksheet and its change. So whenever there is new entry or deletion (any change) in the sheet, it refresh all the pivot tables attached to it -
Private Sub Worksheet_Change(ByVal Target As Range)
ThisWorkbook.RefreshAll
End Sub
( I am not very familiar with the VBA or office script code, so sorry for basic question.)
But this does not work on excel online. Hence i need a code to use in excel online code editor (or typescript). So Far, I am able to write this code -
async function main(workbook: ExcelScript.Workbook) {
await Excel.run(async (context) => {
console.log("Adding Sheet OnChange Handler");
let mysheet = context.workbook.worksheets.getItem("Attendance");
mysheet.onChanged.add(ref);
await context.sync();
console.log("Added a worksheet-level data-changed event handler.");
}
)};
function ref(workbook: ExcelScript.Workbook) {
let selectedsheet = workbook.getActiveWorksheet();
selectedsheet.refreshAllPivotTables();
console.log("Pivot Refreshed.");
};
I am getting an error Cannot find name 'Excel' and it should work whenever there is any change in the worksheet which is not the case. Please help me with this.
Thanks.
I think you are missing the () at the end of the refreshAllPivotTables method.
Please try this -
function main(workbook: ExcelScript.Workbook) {
workbook.refreshAllPivotTables(); // Refresh all pivot tables
}
As replied by #Daniel G. Wilson , it is not possible in script right now. So I used the Power Automate approach.
I wrote the script in my code editor and saved it-
function main(workbook: ExcelScript.Workbook) {
let selectedsheet = workbook.getWorksheet("Pivot");
selectedsheet.refreshAllPivotTables();
console.log("Pivot Refreshed");
};
Then I created a Scheduled flow in Power Automate. Steps are -
Create new Scheduled flow.
Give some name.
Set the starting time and the interval to run it automatically.
Select new step.
Select Excel Online Business.
Select Run a Script.
Choose file location and Script name.
Save and test the flow.
It works fine. Thanks.

Resources