您可以使用 xlcOnKey 和 ExcelDNA 在另一个代码文件中指定方法吗

can you specify a method in another code file using xlcOnKey and ExcelDNA

我可以在同一代码文件/命名空间中成功注册一个方法到 excel 键击,就像这样:

XlCall.Excel(XlCall.xlcOnKey, "^t", "TESTMETHOD");

我能否以某种方式在另一个文件的不同静态 class 中指定一个方法?例如:

XlCall.Excel(XlCall.xlcOnKey, "c", "utilClass.TESTMETHOD");

当我尝试此操作时 Excel 告诉我“无法 运行 宏 utilClass.TESTMETHOD。该工作簿中可能没有该宏,或者所有宏都被禁用。

是的,你可以。 class 的名称在使用 Excel-DNA 的默认注册机制时不相关(这似乎是你的情况)。

默认情况下,Excel-DNA 会在 public classes 中扫描您的加载项程序集以查找静态方法,并自动将它们注册为 命令 or functions with the name as the method name without considering the name of the class the method属于.

这意味着当您将 TESTMETHOD 移动到名为 utilClass 的 class 时,它仍然会在 Excel 中注册为 TESTMETHOD,因此,您的注册码保持不变,即使方法在不同 class:

XlCall.Excel(XlCall.xlcOnKey, "^t", "TESTMETHOD");

如果你想为你的命令定义一个自定义名称,你可以使用添加 ExcelCommand 属性并设置你想要的名称(下面的例子)或者你可以使用 Excel-DNA Custom Registration library 如果您想对注册有更多的控制权。

public static class UtilClass
{
    [ExcelCommand(Name = "UtilClass.TestMethod")]
    public static void TestMethod()
    {
        // ...
    }
}

public class MyAddIn : IExcelAddIn
{
    public void AutoOpen()
    {
        XlCall.Excel(XlCall.xlcOnKey, "^t", "UtilClass.TestMethod");
    }

    // ...
}

值得一提的是,您可以直接在ExcelCommand属性中轻松定义快捷方式,而无需调用XlCall.Excel来注册快捷方式...例如

public static class UtilClass
{
    [ExcelCommand(Name = "UtilClass.TestMethod", ShortCut = "^t")]
    public static void TestMethod()
    {
        // ...
    }
}

上面会自动注册一个名为UtilClass.TestMethod的命令,可以通过CTRL + T.[=21触发=]