简体   繁体   中英

VSTO Excel.DropDown event

I am adding dynamically an Excel.DropDown within a ActiveSheet cell using C# VSTO. Is there a way to handle a change selection event without embedding a macro to workbook? Alternatively I would be interested to use Excel's data validation technique (cell.Validation), where presumably I would need to work with SheetChange event. Not sure which one is more efficient? The code I am using is bellow

var currentSheet = Application.Sheets[strDestSheetName];
var inv = Application.Sheets[strSrcSheetName];
var items = inv.Range[strSrcRange];
var list_items = new List<string>();

foreach (Excel.Range cell in items)
{
    list_items.Add(cell.Value2.ToString());
}

Range xlsRange;
xlsRange = currentSheet.Range[strDestCell];

Excel.DropDowns xlDropDowns;
Excel.DropDown xlDropDown;
xlDropDowns = ((Excel.DropDowns)(currentSheet.DropDowns(Missing.Value)));
xlDropDown = xlDropDowns.Add((double)xlsRange.Left, (double)xlsRange.Top, (double)xlsRange.Width, (double)xlsRange.Height, true);

//Add item into drop down list
for (int i = 0; i < list_items.Count; i++)
{
    xlDropDown.AddItem(list_items[i], i + 1);
}
xlDropDown.OnAction = "SomeMacroCode";

you can use Excel's data validation technique in this way:

var activeSheet = (Worksheet) Globals.ThisAddIn.Application.ActiveSheet;
            int lastUsedCell = activeSheet.UsedRange.Rows.Count;
//in this example we dynamicly add drop down list to second colomn
            string columnName = "B" + lastUsedCell;
//the range is from second colomn of first row to last row          
      Range range = activeSheet.Range["B1", columnName];
   var list=new List<string>();
                    list.Add("a");
                    list.Add("b");
                    string items= string.Join(",",
                        list);
                    range.Validation.Add(XlDVType.xlValidateList, Type.Missing,
                        XlFormatConditionOperator.xlBetween, items);
                    InsertingTypeNotificationLable.Visible = true;
                    SendButton.Enabled = true;

also you can have dynamicly populated drop down list at run time, for example whenever user click a button in your task pane

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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