CodeMonkey
CodeMonkey

Reputation: 12444

how to get the cell column of a range

I'm iterating over a row which I got from a range in order to find a specific word in the cell content and then I want to get the column where I find it. For example, if I find the desired content at the 19th place, it means the the excel column is "S".

Here is the code I'm using so far:

Excel.Worksheet xlWorkSheet = GetWorkSheet(currentWorkBook, "sheet");
var row = xlWorkSheet.Rows["5"];
int rowLength = xlWorkSheet.UsedRange.Columns.Count;
Excel.Range currentTitle = row[1]; //in order to iterate only over the 5th row in this example
  for (int i = 1; i < rowLength; i++)
  {
    string title = currentTitle.Value2[1,i];
    if (title == null)
    {
      continue;
    }
    if (title.Contains(wordToSearch))
    {
      string column = THIS IS THE QUESTION - WHAT DO I NEED TO WRITE HERE?
      Excel.Range valueCell = xlWorkSheet.Range[column + "5"];
      return valueCell.Value2;
    }

notice the line of string column in which i need to add the code.

Upvotes: 0

Views: 3937

Answers (1)

user2480047
user2480047

Reputation:

As far as you don't want to rely on any calculation, the other option I see is extracting the column letter from Address property, like in the code below:

Excel.Range currentRange = (Excel.Range)currentTitle.Cells[1, i];
string columnLetter = currentRange.get_AddressLocal(true, false, Excel.XlReferenceStyle.xlA1, missing, missing).Split('$')[0];
string title = null;
if (currentRange.Value2 != null)
{
     title = currentRange.Value2.ToString();
}

As you can see, I am forcing a "$" to appear in order to ease the column letter retrieval.

Upvotes: 1

Related Questions