2015-12-29 91 views
0

我使用C#VSTO在ActiveSheet單元格內動態添加Excel.DropDown。有沒有辦法處理更改選擇事件,而無需將宏嵌入工作簿?或者我會有興趣使用Excel的數據驗證技術(cell.Validation),在那裏大概我需要使用SheetChange事件。不知道哪一個更有效率? 我使用的代碼是波紋管VSTO Excel.DropDown事件

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"; 

回答

1

你可以使用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; 

,你也可以有動態地填充下拉列表在運行時,例如每當用戶單擊任務窗格中的按鈕

+0

我同意你的方法,但是不清楚如何處理更改值事件。我寧願避免使用sheet_change事件,Thx – Jim

+0

逗號並不總是正確的分隔符。您應該改用'System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator'。 –