0

I'm trying to figure out how to sort a column in Excel. I read here --> https://learn.microsoft.com/en-us/javascript/api/excel/excel.rangesort?view=excel-js-preview

But they don't give any useful example.

Here is a basic example I'm trying to figure out:

var ws = context.workbook.worksheets.getActiveWorksheet();
ws.getRange("A1").values = "B"
ws.getRange("A2").values = "A"
ws.getRange("A3").values = "C"
await context.sync()

var Used_Range = ws.getUsedRange(true)
await context.sync()
Used_Range.RangeSort.apply()
Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
FreeSoftwareServers
  • 2,271
  • 1
  • 33
  • 57
  • Please provide more details. What do you expect to see when the code runs and what do you actually see? Also, note that RangeSort.apply has several possible parameters and one of them is reqired. – Rick Kirkham Nov 17 '22 at 21:47
  • Intellisense shows im nowhere near, just didn't want to post no code, though this tag hasn't been nearly as mean as others. But I should think the goal is clear, the column A should be sorted Alphanumeric, A,B,C – FreeSoftwareServers Nov 17 '22 at 21:54

1 Answers1

2

This code will sort the range A1:A3 on the active worksheet by the first column in the range:

  await Excel.run(async (context) => {
    const sheet = context.workbook.worksheets.getActiveWorksheet();

    // Add values to the range
    const range = sheet.getRange("A1:A3");
    range.values = [["B"], ["C"], ["A"]];

    // Sort the range
    const sortFields = [
      {
        key: 0,
        ascending: true
      }
    ];
    range.sort.apply(sortFields);

    await context.sync();
 });

The difference between your code and this code is that the range.sort.apply method need to know which column to sort by and the sortfields array provide that information. Also, the method should be called before the context.sync() method is called.