Search code examples
c#.netexcelexcel-dna

Static functions work but not onKey events in Excel-DNA


This is my code,

public class Main : IExcelAddIn
{

        public void AutoOpen()
        {
            dynamic app = ExcelDnaUtil.Application;
            app.OnKey("^N", "FormatNumbers");
        }

        public void AutoClose()
        {
        }

    }

    public class KeyboardShortcuts
    {

        public static void FormatNumbers()
        {
            dynamic app = ExcelDnaUtil.Application;
            dynamic selection = app.Selection;
            selection.NumberFormat = "#,##0;[Red]-#,##0";
        }
    }

    public static class MyFunctions
    {
        [ExcelFunction(Description = "My first .NET function")]
        public static string SayHello(string name)
        {
           return "Hello " + name;
        }
    }

}

I am currently building the above class using .NET 8.0 and to a Windows-7.0 platform. After reading the docs, I see that only .NET 6.0 is supported.

However, the project builds just fine and the static SayHello function works properly.

The problem I have is that the FormatNumbers class does not. I the following error message,

Cannot run the macro "FormatNumbers". The macro may not be available or all the macros may be disabled.

Some functions are working, so clearly it's not a permissions or antivirus problem. I have set Trust Center settings to let all macros run and the addin folders (subfolders included) to be trusted, but still no luck.

Error

I'd appreciate any help debugging this issue.

Thank you in advance.


Solution

  • You can try

    [ExcelCommand(ShortCut="^N")]
    public static void FormatNumbers()
    {
      ...
    }
    

    or using the C API instead of the COM interface

    XlCall.Excel(XlCall.xlcOnKey, "^N", "FormatNumbers");