microsoft / advanced-formula-environment

Create, edit, and reuse formulas in Excel
https://aka.ms/get-afe
MIT License
109 stars 11 forks source link

Import module from Name Manager #56

Open KDean-Dolphin opened 9 months ago

KDean-Dolphin commented 9 months ago

I have a large library of functions (~100) that I developed for a specific problem domain and I would like to package them as a module to distribute via Gist. It would be nice to be able to create a module from existing names (functions and formulas), but there's doesn't appear to be a way to do that.

The feature should recognize module names, as I have already stored my functions as ModuleName.FunctionName, which would mean stripping off ModuleName when bringing them over from Name Manager.

For now, I don't have much of a problem, as I maintain the functions in a worksheet and use some rudimentary VBA to publish them, so it will be easy for me to export them in module format. It would be nice in the future, though.

jack-williams commented 9 months ago

Adding as an enhancement request.

The logic can be written using Script Lab if needed.

$("#run").click(() => tryCatch(run));

const modulePrefix = "tester";

async function run() {
  return Excel.run(async (context) => {
    const names = context.workbook.names.load({ name: true, formula: true, comment: true });
    await context.sync();
    const definitions = names.items.filter(x => x.name.startsWith(modulePrefix + "."));
    const bindings = definitions.map((n) => {
      let content = ""
      if (n.comment !== undefined && n.comment !== "") {
        content += `/** ${n.comment} */`;
        content += "\n";
      }
      content += `${n.name.substring(modulePrefix.length + 1)} ${n.formula};`
      return content
    });
    console.log(bindings.join("\n\n"));
  });
}

/** 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);
  }
}

In the default "New Snippet" you can drop this code and the run button will create a module definition for the "tester" module.