Search code examples
c#excelcell

Finding a cell in Excel using its keywrod in Name Box without Searching


I can find a cell in Excel using its row and column number likes the following code in C#:

var option_cell = xlRange.Cells[row_counter, column_counter];

Also, there is a unique name for each cell in Excel which is written in Name Box:

Excel Name Box

Now the question is how can I get a cell using its name in C# such as what I did using its row and column number (preferably a suggestion in Microsoft.Office.Interop.Excel;)?


Solution

  • I found an answer usingget_Range function such as the following:

    Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; 
    string key = "Keyword";           
    var xlRng = xlWorksheet.get_Range(key, key);
    var value = xlRng.Value.ToString();
    

    Or if you want to get the text of the cell, you can using the following code:

    Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; 
    string key = "Keyword";           
    var xlRng = xlWorksheet.get_Range(key, key);
    var cell = xlRng.Cells[1,1];
    var value = cell.Text;
    

    Although, a problem with this solution is we should know the sheet number to find the keyword and it does not work to find the cell in the whole of the excel file. To solve this problem, I've searched all sheets to find the keyword:

     private string get_cell_text_by_keyword(Excel.Workbook xlWorkbook, string keyword)
     {
          foreach(Excel._Worksheet sheet in xlWorkbook.Sheets)
          {
               try
               {
                    var xlRng = sheet.get_Range(keyword, keyword);
                    var cell = xlRng.Cells[1, 1];
                    return cell.Text;
               }
               catch (Exception exp)
               {
               }
          }
          throw new Exception("this keyword '" + keyword + "' was not found");
     }