How to get the column index of the current cell?

Shane LeBlanc picture Shane LeBlanc · Nov 29, 2012 · Viewed 11.4k times · Source

I have this code here...

For Each cell In worksheet.Cells(8, 2, lastRow, lastCol)
    Select Case "What Goes Here"
    End Select
Next

I want to verify the column that the current cell is in. I can use...

cell.Address

but that returns a string with both the column letter and row. Would there be another way of getting maybe just the index or letter only of the column or would I just have to do something like....

If cell.Address.Contains("A")

Answer

Tim Schmelter picture Tim Schmelter · Nov 29, 2012

You get it via cell.Start.Column:

int colIndex = cell.Start.Column;

Start is always the same as End when you use foreach.

The same if you want the row-number instead:

int rowNum = cell.Start.Row;

Note that the column- and rows are not zero based indices but 1-based. So the first column of the first row has Row=1 and Column=1.