简体   繁体   English

使用 VB.NET 在 Excel 的下拉单元格中获取可用选项

[英]Getting the available choices in a dropdown cell in Excel using VB.NET

I'm looking into getting the all possible values of a dropdown cell in Excel using VB.NET.我正在研究使用 VB.NET 在 Excel 中获取下拉单元格的所有可能值。 Basically here is my code...基本上这里是我的代码...

Dim excel As New Microsoft.Office.Interop.Excel.Application()
Dim pvw = excel.Workbooks.Open(TextBox1.Text)
Dim wb As Microsoft.Office.Interop.Excel.Workbook = pvw
Dim ws As Microsoft.Office.Interop.Excel.Worksheet = TryCast(wb.Sheets(1), Microsoft.Office.Interop.Excel.Worksheet)

'ws.Range("E9").Value is a dropdown cell and I want to loop through all the available values

wb.Close(True)
excel.Quit()
releaseObject(excel)

I just want to know what possible values there are in the dropdown so I can validate the data.我只想知道下拉列表中有哪些可能的值,以便验证数据。 How do I do this in either VB.NET or C#?如何在 VB.NET 或 C# 中执行此操作? Thank you so much.非常感谢。

Often times the easiest way to figure out the right VB code is to open up the macro (VBA) editor in the source Excel sheet and browse the properties.通常,找出正确 VB 代码的最简单方法是在源 Excel 工作表中打开宏 (VBA) 编辑器并浏览属性。 Doing that, I was able to see a Validation property on a range with a drop-down validation and saw the source range (in my case it was "=$A$1:$A$3" ) on the Formula1 property of that validation.这样做后,我能够在带有下拉验证的范围内看到Validation属性,并在该验证的Formula1属性上看到源范围(在我的情况下是"=$A$1:$A$3" )。 So you could get the range reference easily:因此,您可以轻松获得范围参考:

String source_ref = ws.Range("E9").Validation.Formula1

From there, get the range object from the formula and loop through its cells to get the values.从那里,从公式中获取范围对象并循环遍历其单元格以获取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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