Is it possible to use Excel Worksheet Functions in ExcelScript? - excel

I want to know how a worksheet function can be called in an ExcelScript.
Here it is explained for VBA: https://www.automateexcel.com/vba/worksheet-functions-in-macro/
You can get an application-object in ExcelScript, but it seems that none of the functions can be called:
function main(workbook: ExcelScript.Workbook) {
let app = workbook.getApplication();
}

Related

Referencing another Workbook in Office Scripts

I have a Workbook that requires it to interact with another workbook. I have the below code which will run fine and get the value of the cell. But I need there to be a function to reference another Workbook.
function main(workbook: ExcelScript.Workbook) {
// Get Worksheet
let Sheet1 = workbook.getWorksheet('Worksheet 1');
// Get the value of cell A1.
let range = SourceData1.getRange("A1");
// Print the value of A1.
console.log(range.getValue());
}
I've tried referencing like so...
let SourceData1 = workbook.getWorksheet('https://mydomain.sharepoint.com/personal/Documents/[sourceData.xlsx]in');
But I take it the workbook part just references whatever is open? How do I refer an external workbook from a different sheet?
You should be able to use most of the response I wrote here. There are just a few small differences:
You do not need to stringify or parse anything. You can just work with the value of the cell as a string directly.
You would get the value of the cell in the first script using the range's GetValue method. You would then return that value as a string in the first script like so:
//first script
function main(workbook: ExcelScript.Workbook): string
{
let sh: ExcelScript.Worksheet = workbook.getActiveWorksheet();
let rang: ExcelScript.Range = sh.getRange("E1");
return rang.getValue() as string
}
In the second script, you wouldn't need to resize any ranges. Just set the range where the input value should be assigned, and assign the functions' parameter value to that (in my link I called the parameter tableValues. So since this is a cell value, I'd consider renaming it to something like cell value). So if you had a cellValue parameter you could just update the line of code like so:
//second script
function main(workbook: ExcelScript.Workbook, cellValue: string)
{
let sh: ExcelScript.Worksheet = workbook.getActiveWorksheet()
let rang: ExcelScript.Range = sh.getRange("D1")
rang.setValue(cellValue)
}

addChart not working how "Record Actions" recorded it

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);
}

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