In a VSTO C# project I want to get a range of rows from a set of row indexes.
The row indexes can be for example like "7,8,9,12,14".
Then I want the range "7:9,12,14" rows.
I now do this:
Range rng1 = sheet.get_Range("A7:A9,A12,A14", Type.Missing);
rng1 = rng1.EntireRow;
But it's a bit inefficient due to string handling in range specification.
sheet.Rows["7:9"]
works but I can't give this
sheet.Rows["7:9,12,14"] // Fails
You can find a named range by using the Go To feature—which navigates to any named range throughout the entire workbook. You can find a named range by going to the Home tab, clicking Find & Select, and then Go To. Or, press Ctrl+G on your keyboard.
To select a larger range, it's easier to click the first cell and hold down the Shift key while you click the last cell in the range.
I am not an expert in C# but AFAIK you have to use the EntireRow as you have done above. The string that you are looking for can be achieved from the .Address
property. For example
private void button1_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Range xlRange;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Excel.Application();
xlWorkBook = xlexcel.Workbooks.Add();
// Set Sheet 1 as the sheet you want to work with
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlRange = xlWorkSheet.get_Range("A7:A9,A12,A14", misValue);
MessageBox.Show(xlRange.EntireRow.Address);
xlRange = xlWorkSheet.get_Range(xlRange.EntireRow.Address, misValue);
MessageBox.Show(xlRange.Address);
}
So you can write the above as
private void button1_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Range xlRange;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Excel.Application();
xlWorkBook = xlexcel.Workbooks.Add();
// Set Sheet 1 as the sheet you want to work with
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlRange = xlWorkSheet.get_Range("$7:$9,$12:$12,$14:$14", misValue);
MessageBox.Show(xlRange.Address);
}
See the part
xlRange = xlWorkSheet.get_Range("$7:$9,$12:$12,$14:$14", misValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With