Search code examples
c#excel-dna

Write to current cell from toolbar activation in Excel-DNA


I have a function which gets run from a button on a toolbar.

The button loads a windows form which allows the user to perform a product lookup and returns the product code:

Ribbon:

          <button id='btnProductLookup' label='Product Code Lookup' image='ProdCode' size='large' onAction='ProductCodeLookup'/>

Method:

    public void ProductCodeLookup(IRibbonControl control)
    {
        using (FrmProductLookup lookup = new FrmProductLookup(_callHandler))
        {
            DialogResult result = lookup.ShowDialog();
            if (result == DialogResult.OK)
            {
                ExcelReference current = XlCall.Excel(XlCall.xlfActiveCell) as ExcelReference;
                MessageBox.Show(current.ColumnFirst.ToString());
                MessageBox.Show(lookup.SelectedProductCode);
            }

        }
    }

I want to write the value in lookup.SelectedProductCode into the currently selected cell but I get an exception every time.


Solution

  • The C API (XlCall.Excel) is not directly available in a ribbon handler.

    You can either transition to a macro context using ExcelAsyncUtil.QueueAsMacro(...) or use the COM object model in this setting.