Office Script "Delete All Rows Except The First Header Row" in Excel - excel

I Try to create a office script, that do the same as this excel makro:
Sub clear()
Rows("2:" & Rows.Count).ClearContents
End Sub
my office Script looks like this:
function main(workbook: ExcelScript.Workbook)
{
let table = workbook.getTable("Table1");
let rowCount = workbook.getTables()[0].getRowCount();
table.deleteRowsAt(2, rowCount);
}
i get following error:
Line 9: Cannot read property 'deleteRowsAt' of undefined
i dont get why the property "deleteRowsAt" is undefined.
it needs to be a office script, because i want to automate a process with power automate.

Not sure why you didn't use table in your rowCount code. You don't know if you are even getting that table for sure.
Assuming your table starts in Row 2 and the headers are in Row 1, to delete the table, see the following code below.
function main(workbook: ExcelScript.Workbook) {
let table = workbook.getTable("Table1");
let rowCount = table.getRowCount();
table.deleteRowsAt(0, rowCount);
}

the office Script works, u need to check if the Table name is really your table name

Related

Excel Office Script not clearing cells. Getting unreachable code detected (7027) error

I have this script which works all except for the clearing of the B4:B120 area "// Clear the "Margin Updates" column." section which is greyed out for some reason):
function main(workbook: ExcelScript.Workbook): ReportImages {
// Recalculate the workbook to ensure all tables and charts are updated.
workbook.getApplication().calculate(ExcelScript.CalculationType.full);
// Get the data from the "Target Margins - FHM" table. (name of Excel tab, not name of table)
let sheet1 = workbook.getWorksheet("Sheet1");
const table = workbook.getWorksheet('Target Margins - FHM').getTables()[0];
const rows = table.getRange().getTexts();
// Get only the Product Type and "Margin Update" columns, then remove the "Total" row.
const selectColumns = rows.map((row) => {
return [row[0], row[1]];
});
// Delete the "ChartSheet" worksheet if it's present, then recreate it.
workbook.getWorksheet('ChartSheet')?.delete();
const chartSheet = workbook.addWorksheet('ChartSheet');
// Add the selected data to the new worksheet.
const targetRange = chartSheet.getRange('A1').getResizedRange(selectColumns.length - 1, selectColumns[0].length - 1);
targetRange.setValues(selectColumns);
// Get images of the chart and table, then return them for a Power Automate flow.
const tableImage = table.getRange().getImage();
return { tableImage };
// Clear the "Margin Updates" column.
const targetSheet = workbook.getActiveWorksheet();
const getRange = targetSheet.getRange("B4:B120");
getRange.clear(ExcelScript.ClearApplyTo.contents);`
}
// The interface for table and chart images.
interface ReportImages {
tableImage: string
}
The code copies the data in sections of the A and B columns (which constitute a table) and sends an email via Power Automate flow. Unfortunately, I need the section of the B column to be clear of values (not formatting or style) after which this flow is not doing.
I'd greatly appreciate help with this problem.
Thank you.
#cybernetic. nomad:
When I try using Range ("B4:B120").Clear I receive
unreachable code detected (7027)
and
and "cannot find name 'Range' (2304)
Office Script Range Clear Error
In JavaScript, the function exits as soon as the return keyword is evaluated. That's why it's saying your code is unreachable. So you have to restructure your code so that the return happens at the end. So you can update your code to look something like this:
// Clear the "Margin Updates" column.
const targetSheet = workbook.getActiveWorksheet();
const getRange = targetSheet.getRange("B4:B120");
getRange.clear(ExcelScript.ClearApplyTo.contents);
return { tableImage };

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

Excel Script: Cannot read property 'getRowCount works not with Power Automate

I wrote I simple Excel Script which works online pretty well, but if I use the same Script with Power Automate I get an error.
Here ist the Script:
function main(workbook: ExcelScript.Workbook)
{
let sheet = workbook.getActiveWorksheet();
let range = sheet.getUsedRange();
let rows = range.getRowCount();
let cols = range.getColumnCount();
for (let row = 2; row <= rows; row++) {
}
}
I am getting the message: Runtime error Line 5: Cannot read property 'getRowCount' of undefined
Does anybody know why this message occurs only with Power Automate and how to solve it?
I’ve been told to stay away from using “workbook.getActiveWorksheet” and ActiveCell when using Power Automate. Instead you can use
workbook.getWorksheets()[0]
Or
workbook.getWorksheet(“Sheet1”)
If that isn’t the problem, then maybe you can try to get the UsedRange in a better way.
If you use
sheet.getUsedRange(true)
getUsedRange has an optional Boolean parameter to get values only.
getUsedRange documentation

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 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