• If you would like to post, please check out the MrExcel Message Board FAQ and register here. If you forgot your password, you can reset your password.
  • Excel articles and downloadable files provided in the articles have not been reviewed by MrExcel Publishing. Please apply the provided methods / codes and open the files at your own risk. If you have any questions regarding an article, please use the Article Discussion section.
Worf

Classes with Excel Script Lab

Excel Version
  1. 365
There are at least three ways to automate Excel: VBA, Office Scripts and Script Lab.
This article will show how to use TypeScript and Script Lab to perform repetitive spreadsheet tasks. From the Internet:
*************************************************************************
What is Script Lab?
Wouldn't it be crazy if you could launch Excel, click to open a small code window, and then instantly start writing and executing JavaScript that interacts with your spreadsheet?
Script lab is a tool for anyone who wants to learn about writing Office Add-ins for Excel, Outlook, Word, or PowerPoint. The focus is the Office JavaScript API, which is the technology you need for building Office Add-ins that run across platforms. Maybe you're an experienced Office developer and you want to quickly prototype a feature for your add-in. Or maybe you've never tried writing code for Office and you just want to play with a sample and tweak it to learn more. Either way, Script Lab is for you.
*************************************************************************

Classes are important structures in several programming languages, including JavaScript and TypeScript. The sample code below includes examples on how to:
  • Extend a class.
  • Return a different number of parameters than originally defined
  • Use a class to implement an interface
  • Declare an abstract class
The code itself is straightforward, just doing some range manipulations and writing to the sheet.

JavaScript:
$("#run").on("click", () => tryCatch(run));
async function run() {
await Excel.run(async (context) => {
const sheet = context.workbook.worksheets.getActiveWorksheet();
const mat = sheet.getRange("b2").getSurroundingRegion()
mat.load("rowCount,values,formulas,address")
await context.sync()
let matv = mat.values
const lastc = mat.getLastCell()
lastc.load("values,address")
await context.sync()
var rn = 10
var fs: string = ""
class adult {
  protected sheet2 = sheet
  action1() {
  sheet.getRange("b" + rn).values = [["Action1: " + lastc.address]]
  rn++
  lastc.values = matv[1][0]
  }
}
class woman extends adult {
  public esp = 2
  protected p = 3       // class and subclass
  protected static readonly vans = matv[3][3]
  action2() {
  const v: number = matv[4][2]
  this.sheet2.getRange("b" + rn).values = [["Action2: " + matv[2][2] + matv[3][2] + v + " at " + this.sheet2.name]]
  rn++
  this.sheet2.getRange("b" + matv[5][0]).values = [[100]]
  }
}
const tc = new woman()
let uni = mat.getResizedRange(-2, -3).getLastCell()
uni.values = [[300]]
sheet.load("values,name")
await context.sync()
matv[1][0] > matv[2][0] ? tc.action1() : tc.action2()
let Lv = matv[1][0]
sheet.getRange("b" + rn).values = [[JSON.stringify(Lv, null, 4)]]
rn++
// *************
class GT {
  private vals: number[] = []      // only for this class
  addg(...var4: number[]) {
  this.vals.push(...var4)
  return this.vals.length
  }
}
class GC {
  countg(s2: string[], one: string) {
  return s2.filter(val => val === one).length
  }
}
class FC extends GC {
  countg2(sa: string[]) {
  return super.countg(sa, Lv)
  }
}
const fv = new GT()
sheet.getRange("b" + rn).values = [["Row count is " + mat.rowCount]]
rn++
var td: number[] = []
for (let i = 0; i < mat.rowCount; i++) {
td.push(matv[i][2])
}
let av = fv.addg(...td)
sheet.getRange("b" + rn).values = [["length is " + av]]
rn++
const counter = new FC()
td = []
var tds: string[] = []
for (let i = 0; i < mat.rowCount; i++) {
tds.push(matv[i][3])
}
const count = counter.countg2(tds)
sheet.getRange("b" + rn).values = [["count is: " + count]]
rn++
class line {
  nocheck: string[]
  init(pend: string[]) {
  this.nocheck = pend
  }
  proceed() {
  return this.nocheck.pop()
  }
}
const acts = new line()
tds = []
for (let i = 0; i < mat.rowCount; i++) {
tds.push(matv[i][4])
}
acts.init(tds)
sheet.getRange("b" + rn).values = [["next is " + acts.proceed()]]
rn++
class SB {
  getval() {
  return [matv[1][5], matv[0][5]]
  }
}
function useSB(veh: SB) {
fs = "getval length is " + veh.getval().length
}
const sbv=new SB
const res=sbv.getval()
//console.log(res.length)   // result is 2
useSB({ getval: () => matv[2][5] })
sheet.getRange("b" + rn).values = [[fs]]
rn++
interface child {
name: string; eval(hours: number): void
}
fs = ""
class foreign implements child {
  name: string
  constructor(name2: string) {
  this.name = name2
  }
  eval(measure: number): void {
  for (let i = 0; i < measure; i += 1) {
  fs = fs + bel.name + i + "/"
  }
  }
}
const bel = new foreign(matv[1][6])
bel.eval(2)
sheet.getRange("b" + rn).values = [[fs]]
rn++
abstract class company {
  readonly name: string
  constructor(name2: string) {
  this.name = name2
  }
  abstract getst(): string[]
}
class mining extends company {
  getst(): string[] {
  return [matv[2][7]]
  }
}
let mys: company
mys = new mining(matv[1][7])
sheet.getRange("b" + rn).values = [[mys.getst() + " / " + mys.name]]
rn++
sheet.getRange("b" + rn).values = [["finished"]]
await context.sync();
});
}
    
/** Default helper for invoking an action and handling errors. */
async function tryCatch(callback) {
  try {
  await callback();
  } catch (error) {
  // Note: In a production add-in, you'd want to notify the user through your add-in's UI.
  console.error(error);
  }
}

Copy of Script-Lab--a-Microsoft-Garage-project22.xlsx
BCDEFGHI
2Column1Column2Column3Column4Column5Column6Column7Column8
3F15AeatmagicZaramagnesium
4B26CrunabcdeabcdeJoancobalt
510027F300AmericaTomcloud
63229CjogEuropeAlbertbenchmark
75333FcleanAsiaMarinaF
8
9
10Action1: Sheet2!I7
11"F"
12Row count is 6
13length is 6
14count is: 2
15next is clean
16getval length is 10
17Zara0/Zara1/
18cobalt / magnesium
19finished
Sheet2
Author
Worf
Views
373
First release
Last update
Rating
0.00 star(s) 0 ratings

More Excel articles from Worf

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top