如何从c或vb.net读取Excel下拉列表或复选框的值?

如何从c或vb.net读取Excel下拉列表或复选框的值?,.net,excel,interop,.net,Excel,Interop,我正在使用Microsoft.Office.Interop.Excel读取工作表单元格的值,但找不到显示如何读取下拉列表、复选框和选项按钮的信息 谢谢 显然,直接访问下拉列表集合是非常困难的。解决方法是访问包含下拉列表的单元格的Validation属性,获取其公式,然后解析出列表的位置 string selectedText = myDropDown.get_List(myDropDown.ListIndex); Excel.Range dropDownCell = (Excel.Range)

我正在使用Microsoft.Office.Interop.Excel读取工作表单元格的值,但找不到显示如何读取下拉列表、复选框和选项按钮的信息


谢谢

显然,直接访问下拉列表集合是非常困难的。解决方法是访问包含下拉列表的单元格的Validation属性,获取其公式,然后解析出列表的位置

string selectedText = myDropDown.get_List(myDropDown.ListIndex);
Excel.Range dropDownCell = (Excel.Range)ws.get_Range("A1", "A1"); //cell containing dropdown
string formulaRange = dropDownCell.Validation.Formula1;
string[] splitFormulaRange = formulaRange.Substring(1,formulaRange.Length-1).Split(':');

Excel.Range valRange = (Excel.Range)ws.get_Range(splitFormulaRange[0], splitFormulaRange[1]);
for (int nRows = 1; nRows <= valRange.Rows.Count; nRows++) {
    for (int nCols = 1; nCols <= valRange.Columns.Count; nCols++) {
         Excel.Range aCell = (Excel.Range)valRange.Cells[nRows, nCols];
     System.Console.WriteLine(aCell.Value2);
    }
}

经过一番努力,我得到了以下内容,只适用于下拉列表。我也有一个类似但不完全相同的单选按钮解决方案,但没有尝试复选框

互操作返回一个System.Object并没有使这一点变得更容易,在这里,人们期望数组与调试器在技术上是一个System.Object[*]——但不管是什么,我不能像解析数组一样解析它,也不能像解析ControlFormat.List[]数组那样进行1索引。万岁

下面的代码假定一个打开的工作簿和目标下拉列表的名称

Worksheet worksheet = (Worksheet)workbook.Worksheets[worksheetName];

var control = worksheet.Shapes.Item(dropdownName).ControlFormat;
var vl = GetDropdownList(control);

var targetIndex = IndexOfMatch(targetValue, vl);
control.Value = targetIndex;


// control.List returns a System.Object that may indeed be an array, but it's hard to parse in that format
// let's loop through it, explicitly casting as we go
private List<string> GetDropdownList(ControlFormat control)
{
    var newList = new List<string>();
    // haw! the Excel control-list is one-indexed! And the last item is equal to the count-index.
    for (int i = 1; i <= control.ListCount; i++)
    {
        newList.Add((string)control.List[i]);
    }

    return newList;
}

private int IndexOfMatch(string targetValue, List<string> vals)
{
    int indexMatch = vals.IndexOf(targetValue);

    // the Excel target is 1-indexed, so increase by one
    return ++indexMatch;
}
我更愿意在OpenXmlSDK中实现这一点,但如果我能想出如何实现这一点,我会选择d****d。我可以找到附加到单元格的DataValidation,解析工作表及其指向的单元格,从SharedStringTable中获取它们的SharedString值——但无论我做什么,我都无法写回任何数据。菲


我从地狱之心向你刺去。

所以,我想我需要获取下拉列表集合,然后获取单个下拉列表,然后获取所选下拉列表的LinkedCell以获取所选索引,然后转到ListFillRange并从LinkedCell中选择索引??是这样做的吗?下拉列表中是否填充了对其他工作表的引用?不,列表与下拉列表位于同一工作表上。以下是一些有用的信息:这给了我一个错误:找不到类型为“dropdown”的公共成员“get_list”。我认为这个答案有点错误,因为它谈到了单元格的验证,OP似乎要求访问MSForms.ComboBox、dropdown等的值。。非单元格验证下拉列表。如果我有一个简单的范围,则此选项有效。如果我有这个公式呢=如果$A9,间接库存!D&MATCHA9&C9,库存!A:A,0。我一直在挠头,但还是拿不到射程。非常感谢。