VSTO Excel.DropDown event
本文关键字:event DropDown Excel VSTO | 更新日期: 2023-09-27 18:28:17
我正在使用C#VSTO在ActiveSheet单元格中动态添加Excel.DropDown。有没有一种方法可以在不将宏嵌入工作簿的情况下处理更改选择事件?或者,我可能有兴趣使用Excel的数据验证技术(cell.validation),在那里我可能需要处理SheetChange事件。不确定哪一个更有效?我使用的代码如下
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";
您可以通过以下方式使用Excel的数据验证技术:
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;
您还可以在运行时动态填充下拉列表,例如每当用户单击任务窗格中的按钮时