C#Interop Excel范围查找第一个和最后一个填充值

时间:2018-08-08 22:18:41

标签: c# excel range vsto office-interop

我有一个范围(一行),我想知道该范围内第一个和最后一个填充值的列位置。这就是我试图计算位置的方法。

var xlRange = (Excel.Range)currentSheet.Cells[10, 1].EntireRow; // 10th row.
long firstColumn= (long)xlRange.get_End(Excel.XlDirection.xlToRight).Column;

表格如下:

enter image description here

firstColumn返回8。这是正确的。但是我不知道如何获取最后填充的单元格的列位置。

long firstColumn= (long)xlRange.get_End(Excel.XlDirection.xlToRight).Column;

按如下所示设置excel时,返回firstColumn的12:

enter image description here

我原本希望得到1。

有指针吗?

1 个答案:

答案 0 :(得分:1)

您可以使用Excel附带的SpecialCells方法。 https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-specialcells-method-excel

根据您的情况,您要查找最后一个单元格,这样: xlCellTypeLastCell 没有值,即Type.Missing

Excel.Range lastCell = workSheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing); 
Excel.Range myRange = workSheet.get_Range("B1", lastCell);

lastCell应该提供其行和列值。
希望这会有所帮助。