Friday, December 1, 2023

Automating Excel with Javascript

Scripts made in class
            
//county data            
function main(workbook: ExcelScript.Workbook) {

  const compare = workbook.getWorksheet("Compare")
  const countyNames = workbook.getWorksheet("CountyNames")
  const dataSet = workbook.getWorksheet("DataSet")

  const selected_county = compare.getRange("A1").getValue()
  console.log("selected_county=" + selected_county)
  
  // searching for the county in Countynames
  const found_cell = countyNames.getRange("D:D").find(selected_county,{completeMatch: true})

  console.log(found_cell.getAddress())
  const row_num = found_cell.getRowIndex()
  console.log("row_num=" + row_num)

  // Insert at range B:B on compare, move existing cells right
  compare.getRange("B:B").insert(ExcelScript.InsertShiftDirection.right);

  // write in the state and county
  compare.getRange("B1").setValue(countyNames.getRangeByIndexes(row_num, 2, 1, 1).getValue())
  compare.getRange("B2").setValue(countyNames.getRangeByIndexes(row_num, 1, 1, 1).getValue())

  compare.getRange("B3").copyFrom(dataSet.getRange(`A${row_num + 1}:CE${row_num + 1}`), ExcelScript.RangeCopyType.all, false, true,);

  compare.getRange("B:B").getFormat().autofitColumns()


    
}


//make_a_chart
function main(workbook: ExcelScript.Workbook) {
  const compare = workbook.getWorksheet("Compare")
  const row = workbook.getSelectedRange().getRowIndex()
  const last_col = compare.getRange("a1").getRangeEdge(ExcelScript.KeyboardDirection.right).getColumnIndex()
  const data_range = compare.getRangeByIndexes(row, 1,1,last_col)
  const cht = compare.addChart(ExcelScript.ChartType.columnClustered, data_range)
  cht.setLeft(380)
  const margin = 10

  let top = margin
  const charts = compare.getCharts()
  if(charts.length > 1){
    top = charts[charts.length - 2].getTop() + charts[charts.length - 2].getHeight()+ margin
  }
  cht.setTop(top)
  compare.getRangeByIndexes(row+1,0,1,1).select()
}

            
            

No comments:

Post a Comment