0

I am doing an ExcelAddin in VisualStudio 2010 for Excel 2007. In my Excel Workbook I have a named range that I call MyRange. It goes from cells C10 to M25. How can I read only the cells that have value in them within MyRange. Note I don´t want to read anything from the other cells, only within MyRange? I want to read the cells that have values in them into a Word document. I think I have that figured out.

I have tried to use UsedRange but that selects everything from A1-M25 ( I only want to select the cells with value from C10-M25). Here is what I got so far.

string FileName = @"C:\MyFile.xlsx";
Excel.Application xlApp = xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet = null;

xlWorkBook = xlApp.Workbooks.Open(FileName);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

object cell1 = "C10", cell2 ="M25";
//Here are some different versions that I tried. I also tried to use the SpecialCell    //method but it didn´t seem to work.
Excel.Range namedRange = (Excel.Range)xlWorkSheet.get_Range("C10", "M25");
Excel.Range last = (Excel.Range)xlWorkSheet.UsedRange;
Excel.Range usedRange = (Excel.Range)xlWorkSheet.get_Range("C10", last);

Any help is highly appreciated. Thank you.

Steini
  • 33
  • 2
  • 7
  • By 'select' do you mean read the value into c# or select in excel? – marvc1 Jul 11 '12 at 15:18
  • Yes, I mean read. Thank you for pointing this out. English is not my first language :) I have changed the question now. – Steini Jul 11 '12 at 16:25

1 Answers1

0

To read each cell value from your 'namedRange' you can loop through the range like this:

foreach (Excel.Range cell in namedRange.Cells)
            {
                if (String.IsNullOrEmpty(cell.Value.ToString()))
                {
                    string thisCellHasContent = cell.Value.ToString();
                    string thisCellAddress = cell.Address.ToString();
                }
            } 
marvc1
  • 3,641
  • 3
  • 25
  • 34
  • Thank you so much for your anwser marvc1. What I want to do next is to write these values into a table in Word. Any ideas of how i would do that? – Steini Jul 12 '12 at 15:53
  • Cool, glad it worked. Mark it as correct answer then! And ask your next question as a new question. – marvc1 Jul 12 '12 at 16:11
  • Sorry I don't have any experience with Word. – marvc1 Jul 12 '12 at 16:13