This office script was running and now shows an error at last line. Any ideas? - office-scripts

{
// Get a worksheet named "Template (2)".
const sheet = workbook.getWorksheet('Template (2)');
// Set its name to Date
let date = new Date(Date.now());
sheet.setName(`${date.toDateString()}`);
}

There are a few rules for worksheet names:
A. You may not name a worksheet using then name of an existing worksheet.
B. Worksheet names may not contain \ / * ? : [ ] see: https://www.mrexcel.com/excel-tips/what-characters-are-legal-in-a-worksheet-name/
toDateString returns something like Thu Sep 29 2022. If you run this script twice in the same day (assuming sheet Template (2) exists both times and the sheet Thu Sep 29 2022 is already present) you will get Worksheet setName: The argument is invalid or missing or has an incorrect format.
You can check if the sheet already exists with:
const sheetName = "sheetNameToTest"
const sheet = workbook.getWorksheet(sheetName);
const sheetExists = sheet !== undefined;
if (sheetExists) {
console.log(`${sheetName} exists!")
}

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

Highlight dates closer than 3 months away

I have a simple spreadsheet listing certificates and expiry dates. Before we moved this to sharepoint online we had a macro than on opening the spreadsheet would check dates in a range of cells and highlight those within three months. It was intended to highlight anything up for renewal before it expired.
I appreciate macros are not an option in Excel online. Can this (or something very similar) be achieved in Office Scripting?
It should be possible to create an Office Script that highlights cells with a date that is within three months of the present.
Something Like:
function main(workbook: ExcelScript.Workbook)
{
// highlight all days between today and the next number of days out
// Number of days to look ahead
const daysOut = 90;
// Excel by default stores dates as the number of days after January 1, 1900
const dayMin = currentDaysSince1900();
const dayMax = dayMin + daysOut;
// Need to target the column to look at and how far down the column
const columnToLookAt = "A";
const rowStart = 1;
const rowEnd = 4;
const rangeAddress = `${columnToLookAt}${rowStart}:${columnToLookAt}${rowEnd}`;
const sheet = workbook.getActiveWorksheet();
// get range column
const range = sheet.getRange("A1:A3");
const values = range.getValues();
// iterate through the rows of values
for (let i =0 ; i < values.length; i++) {
const value = values[i][0];
console.log(value);
if (typeof value === "number") {
// only look at numbers
if (value >= dayMin && value <=dayMax ) {
// highlight
const rangeAddress = `${columnToLookAt}${rowStart +i}`;
const range = sheet.getRange(rangeAddress);
range.getFormat().getFill().setColor("yellow");
}
}
}
}
/**
* Current Days since Jan 1 1900
* Equivalent to number of current excel day
*/
function currentDaysSince1900() {
// method returns the number of milliseconds elapsed since January 1, 1970
const nowMilliseconds = Date.now();
const millisecondsPerDay = 24 * 60 * 60 * 1000 ;
const nowDays = Math.floor(nowMilliseconds / millisecondsPerDay);
const daysBetween1900And1970 = 25567;
const elapsed = nowDays + daysBetween1900And1970 +2; // add two to include both jan 1s
return elapsed;
}
In terms of triggering the script:
Office Script does not currently support running a script on opening a workbook.
You can manually trigger the script whenever you like.
You can also create a Microsoft Power Automate flow to run the script every day to keep the workbook updated.
More Office Script resources:
Official Microsoft Office Script Date Example
Official Microsoft Office Script Examples
wandyezj office script examples

Is it possible to use ClosedXML to read Excel file to Ax 2012?

I have used ClosedXML to create an excel file with 3 worksheets from AX 2012 R3.
I'm wondering if it is possible to use ClosedXML to read the excel file back in to AX?
Yes, that is possible.
Here is the sample code:
ClosedXML.Excel.XLWorkbook workbook;
ClosedXML.Excel.IXLWorksheet worksheet;
ClosedXML.Excel.IXLCells cellsUsed;
ClosedXML.Excel.IXLCell cell;
System.Collections.IEnumerator enumerator;
str value;
;
try
{
workbook = new ClosedXML.Excel.XLWorkbook(#"YourTestFile.xlsx");
worksheet = workbook.Worksheet("SomeEpicSheetName");
cellsUsed = worksheet.CellsUsed();
enumerator = cellsUsed.GetEnumerator();
while (enumerator.MoveNext())
{
cell = enumerator.get_Current();
value = System.Convert::ToString(cell.get_Value());
info(value);
}
}
catch
{
error(AifUtil::getClrErrorMessage());
}
This code creates a message in the InfoLog for each cell filled with a value. You can use it as a start in any new job after changing the used path and sheet name.
This is my example sheet:
The output:

Input/Export data through MS Excel into OATS Scripts

When trying to get the Input the data from the Excel Sheet while working with OATS tool, it always gets into the catch block of the function. The below is the script written. Please help us resolve this issue.
public String getInputfromExcel(int argColumnNumber,int argRowNumber)throws Exception
{
String inputExcelName = dataPath+".xlsx";
String cellContent = "12";
try
{
Workbook workbook = Workbook.getWorkbook(new File(inputExcelName));
Sheet sheet = workbook.getSheet(0);
Cell a1 = sheet.getCell(argColumnNumber, argRowNumber);
cellContent = (a1.getContents()).toString();
System.out.println(cellContent.toString());
workbook.close();
}
catch (Exception e)
{
addReport("Getting Input From Excel", "Fail","Exception while reading value from excel sheet");
}
return cellContent;
}
Axel has brought up the point. On a further note, if I remember correctly, the function sheet.getCell(arg1, arg2) has first argument as rowNumber and 2nd as columnNumber (both the values are 0 based index).
Its old quetion....but just posting answer it might be helpful for someone needy.
In Oracle Application Testing Suite. NO NEED of external JARs to read/write data.
You can enable DataTable module in the tool
Complete explanation given here, http://www.testinghive.com/how-to-read-write-excel-in-oats/
//Define Sheet name to be read, and provide comma seperated to read multiple sheets
String sheetName = "Sheet1";
//Mention excel sheet path
String strFile= "C:\\Demo\\test.xls";
//Defined array list to add Sheets to read
List sheetList = new ArrayList();
sheetList.add(sheetName);
// Iports Sheet1
datatable.importSheets(strFile, sheetList, true, true);
//get rowcount
info("Total rows :"+datatable.getRowCount());
int rowcount=datatable.getRowCount();
//Loop to read all rows
for (int i=0;i<rowcount;i++)
{
//Set current row fromw here you need to start reading, in this case start from first row
datatable.setCurrentRow(sheetName, i);
String strCompany=(String) datatable.getValue(sheetName,i,"Company");
String strEmpFName=(String) datatable.getValue(sheetName,i,"FirstName");
String strEmpLName=(String) datatable.getValue(sheetName,i,"LastName");
String strEmpID=(String) datatable.getValue(sheetName,i,"EmpID");
String strLocation=(String) datatable.getValue(sheetName,i,"Location");
//prints first name and last name
System.out.println("First Name : "+strEmpFName+", Last Name : "+strEmpLName);
//Sets ACTIVE column in excel sheet to Y
String strActive="Y";
datatable.setValue(sheetName, i, datatable.getColumn(sheetName, datatable.getColumnIndex("Active")), strActive);
}
//Updates sheet with updated values ie ACTIVE column sets to Y
datatable.exportToExcel("C:\\Demo\\test1.xlsx");

How to check if cell name exists in activesheet using vb.net

Is it possible to check if a cell name exists (assigned) in the ActiveSheet or not. I tried using XlApp.ActiveSheet.Cells.Name = "bla" . Any help would be appreciated... Thanks in Advance..
I guess you are referring to named ranges?
Let's say you wish to check if there is any named range called "Bla":
for (int i = 1; i <= ActiveWorksheet.Names.Count; i++) {
Excel.Name name = ActiveWorksheet.Names.Item(i);
if (name.Name == ActiveWorksheet.Name + "!Bla") {
// found the named range
}
}
You can also try to access the named range directly, but this will cause an exception if the named range is not present:
var namedRange = ActiveWorksheet.Names.Item("Bla");
Please note, that the name of the named range contains the name of the activeworksheet as well, for example "Sheet1!Bla".
You can do this similarly if the names is saved as a workbook named range.

Resources