如何使用 Excel Interop 从行和列索引中获取范围对象?

How can I get a range object from the row and column index using Excel Interop?

我正在学习 VB.Net 并尝试从 VBA 过渡。如何使用行和列索引检索范围类型的对象?

在 VBA 中,我将使用 Worksheet.Cells([Row,Column]),这将 return 类型为 Range 的对象。
但是使用 Excel 互操作 return 被键入为 Object.
示例:

Dim MyExcel as new Application
Dim MyBook as new Workbook=MyExcel.Workbooks.Open("SomePath\SomeFile.xlsx")
Dim MySheet as new Worksheet=MyBook.Sheets("SomeSheet")
MessageBox.Show(CStr(Sheet2015.Cells(1, 1).Value))

现在,the MSDN for Worksheet.Cells 说:

Because the Item property is the default property for the Range object, you can specify the row and column index immediately after the Cells keyword. For more information, see the Item property.

但是从该页面到项目 属性 的 link 会将您带到 Worksheet.Item,而不是 Range.Item - 所以也许它应该说

"The Item property is the default property for the Worksheet object..."

Worksheet.Item 属性 的 return 是 Object 类型的对象,这解释了为什么我没有智能感知:(

那么我可以使用另一种方法 return 通过提供索引 ( Row,Column) of the cell, instead of the address?

我知道我可以使用 Worksheet.Range 并提供 A1 引用地址,但这对我来说比仅使用行和列索引要复杂得多。

我也知道我可以将 Worksheet.Cells[R,C] 转换为类型 Range,但我更愿意找到一种方法来 return 一个范围。 (请参阅 my other question here 关于将 COM 对象用作基类型 Object

有什么建议吗?

您可以指定 运行ge 如下:

sheetName.Range(sheetName.Cells(row1, col1), sheetName.Cells(row2, col2))

然后你就可以使用这个 运行ge 来做任何你想做的事了。

是的,我意识到这个答案已经很晚了,但我只是 运行 遇到了同样的问题...