簡體   English   中英

如何在以編程方式添加到Excel工作表單元格的xlDropDown中獲取所選項目的值

[英]How to get the value of selected item in a xlDropDown which is added programmatically to a Excel sheet cell

以下代碼顯示了我以編程方式創建下拉菜單的方式。 工作正常。 但是現在我需要獲取單元格特定下拉列表的值。

Microsoft.Office.Interop.Excel.DropDowns xlDropDowns;
Microsoft.Office.Interop.Excel.DropDown xlDropDown;
xlDropDowns = ((Microsoft.Office.Interop.Excel.DropDowns)(sheet.DropDowns(Type.Missing)));
xlDropDown = xlDropDowns.Add((double)rag.Left, (double)rag.Top, (double)rag.Width, double)rag.Height, true);
var DropDownList = {"aaaa","bbbb","cccc","dddd"};

int x = 0;
foreach (var item in DropDownList)
{
    x++;
    xlDropDown.AddItem(item);
}

這就是我嘗試獲取xlDropDown值的方式。 currentCell是我下拉菜單中的單元格

ColumnVal = currentCell.Text; // This didnt give any output

要么

var dd = (Microsoft.Office.Interop.Excel.DropDown)currentCell.DropDowns(Type.Missing);

我知道第二個錯誤,因為單元格范圍和下拉列表是2種不同的東西。 但是我嘗試了所有選項,但仍然找不到任何解決方案。 有人請幫我

更清楚地說,我想訪問一個特定的單元格(currentCell),並包含其中的xldropdown,然后從中獲取價值

首先,您需要參考剛剛添加的下拉菜單:

*假設只有一個下拉菜單,下面將

xlDropDown = ((Excel.DropDown)(xlDropDowns.Item(1)));

那么您需要在確保已選擇某些Excel.DropDown同時訪問.get_List()屬性。

例:

if (xlDropDown.Value > 0)
{
    sht.get_Range("A1").Value = xlDropDown.get_List(xlDropDown.Value);
}
else
{
    throw new Exception("Nothing was selected yet");
}

識別下拉列表:

你可以為一個在每個循環xlDropDowns收集和搶.Name.ListIndex每個xlDropDown

foreach (Excel.DropDown xlDD in xlDropDowns)
{
    MessageBox.Show(xlDD.Name + ", " + xlDD.ListIndex);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM