简体   繁体   English

使用exceldna单击功能区按钮时获取excel选择内容

[英]Get excel selection content when clicking a ribbon button using exceldna

I'm trying to read and update the user's Selection (the excel's range currently selected).我正在尝试读取和更新用户的选择(当前选择的 excel 范围)。 This must happens when the user click on the custom ribbon's button.这必须在用户单击自定义功能区的按钮时发生。 Ribbon works well (basic functions like messagebox triggers fine) but following code fails.功能区运行良好(消息框等基本功能触发良好)但以下代码失败。

[ComVisible(true)]
public class RibbonHandler : ExcelRibbon
{

    public void OnPressMe(IRibbonControl control1)
    {

        ExcelReference ActiveRange = (ExcelReference)XlCall.Excel(XlCall.xlfSelection);

        object[,] dummyData = (object[,])XlCall.Excel(XlCall.xlfValue, ActiveRange);

        int rows = dummyData.GetLength(0);
        int cols = dummyData.GetLength(1);
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                dummyData[i, j] = "foo";
            }
        }

        ExcelAsyncUtil.QueueAsMacro(() => { ActiveRange.SetValue(dummyData); });

    }
}

It triggers an XlCallException at the first line, whatever the size of the selection (one cell, ten cells, one or multiple rows, ...)它在第一行触发XlCallException ,无论选择的大小如何(一个单元格、十个单元格、一行或多行,...)

Many web examples have a range object as function's input, it may be an hint, but I don't understand how clicking a button will sends ActiveSheet.Selection object as parameter in a function.许多 web 示例将范围 object 作为函数的输入,这可能是一个提示,但我不明白单击按钮将如何发送ActiveSheet.Selection object 作为 function 中的参数。

What am I missing to get the user's selection using a Ribbon's button?使用功能区按钮获取用户选择时我缺少什么?

XlCall.Excel is a call to the Excel C API which cannot be done from within the handler of a Ribbon action. XlCall.Excel是对 Excel C API 的调用,不能从功能区操作的处理程序中完成。

You should use the COM object model to interact with the active sheet.您应该使用 COM object model 与活动工作表进行交互。

First, install the NuGet package ExcelDna.Interop so you can get intellisense when accessing the COM object model, then access the current Excel instance through ExcelDnaUtil.Application首先,安装NuGet package ExcelDna.Interop这样访问COM object model 时就可以得到intellisense,然后通过ExcelDnaUtil.Application访问当前的Excel实例

using Excel = Microsoft.Office.Interop.Excel;
// ...

[ComVisible(true)]
public class RibbonHandler : ExcelRibbon
{
    public void OnPressMe(IRibbonControl control1)
    {
        var excel = (Excel.Application)ExcelDnaUtil.Application;
        var selection = (Excel.Range)excel.Selection;

        // ...
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM