Need to find beginning and ending points of an Excel Range in C#

I am not sure what you are trying to do. But here are some examples.

Assume I have the following range:

Excel.Worksheet sheet = this.Application.ActiveSheet as Excel.Worksheet;
Excel.Range range = sheet.get_Range("A1", "B5") as Excel.Range;

To Move your Range Down by n-number of row:

int n = 1;
int rows = range.Rows.Count;
int cols = range.Columns.Count;

Excel.Range newRange = range.get_Offset(n, 0).get_Resize(rows-n,cols);
newRange.Select(); //will select the new range will be 1 row lower

To Move your bottom row up

Excel.Range newRange = range.get_Resize(rows-n,cols);
newRange.Select(); //will select the new range will be 1 row higher

I assume you can figure out how to move it side to side.

get_Offset() will move the whole range over and then you need to resize the range.

EDIT: Now that i know what you want.

To select the Last Cell:

Excel.Range lastCell = range.Cells[rows, cols] as Excel.Range;
lastCell.Select();

Now you can use your own starting point like so:

Excel.Range newRange = sheet.get_Range("B1", lastCell);
newRange.Select();

Ok, found an answer (after nearly 3 hours total searching, asked here 2 hours in), so will post here for others.

Excel.Range urange = (Excel.Range)xlWorkSheet.UsedRange; // gives us the actual range<br>
string used = urange.get_Address(false, false, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);

From the MSDN:

public string get_Address (
    [OptionalAttribute] Object RowAbsolute,
    [OptionalAttribute] Object ColumnAbsolute,
    [OptionalAttribute] XlReferenceStyle ReferenceStyle,
    [OptionalAttribute] Object External,
    [OptionalAttribute] Object RelativeTo)

which apparently the first two are true/false flags, the next is defined as an Microsoft.Office.Interop.Excel.XlReferenceStyle object, and I'm guessing the External is either a reference to an external file, or a flag of some sort. RelativeTo, I can only guess that it refers to an arbitrary position defined, maybe a range object, maybe a string. Unfortunately, the MSDN is extremely sparse on this topic, so I'm just guessing here and posting my guesses. However, using this code as I've posted, I'm able to retrieve the total used as "A1:B245" which gives me exactly what I want, and I can then create a new range by extracting the second part and can then continue on.

Tags:

C#

Excel

Import

Com