Stefan Olsson
Stefan Olsson

Reputation: 647

Excel walking around

Is there a way of walking around in a Excel sheet if you have a reference to a cell ? Like this

Microsoft.Office.Interop.Excel.Range cellWalker = mfe.GetMyCell(Mysheet);

cellWalker = cellWalker.GoUpOneRowButKeepColumn();
cellWalker = cellWalker.GoDownOneRowButKeepColumn();
cellWalker = cellWalker.GoLeftOneColumnButKeepRow();
cellWalker = cellWalker.GoRightOneColumnButKeepRow();

?

Regards Stefan

Upvotes: 2

Views: 3529

Answers (2)

Adam Ralph
Adam Ralph

Reputation: 29956

The Range.Offset property will do this for you. E.g.

Microsoft.Office.Interop.Excel.Range cellWalker = mfe.GetMyCell(Mysheet);

cellWalker = cellWalker.Offset[-1, 0]; // GoUpOneRowButKeepColumn
cellWalker = cellWalker.Offset[1, 0];  // GoDownOneRowButKeepColumn
cellWalker = cellWalker.Offset[0, -1]; // GoLeftOneColumnButKeepRow
cellWalker = cellWalker.Offset[0, 1];  // GoRightOneColumnButKeepRow

Upvotes: 8

The documentation says no. You can probably implement such functionality yourself by wrapping the Interface within your own object. You can write those methods into the object, then use the Range and Cell properties to navigate the sheet.

Conceptual (untested, but "general gist" example)

public class ExcelWalker {
    Microsoft.Office.Interop.Excel.Range navigator
    Microsoft.Office.Interop.Excel.Range currentCells
    Integer currentRow,currentColumn

    public void GoUpOneRowButKeepColumn(){
       currentCells = navigator.Cells(currentRow++,currentColumn);
    }
}

Upvotes: 0

Related Questions