2
votes

I have excel sheets that always look like below

A |  B  |  C
  |     |    
  |     |  something here maybe 
1 |  x  |  k
2 |  y  |  l
3 |  z  |  n
  |  j  |  
  |  j  |  
   ...
  |     |  

I want to get the value of the last non empty cell in A column. A column always starts at A6 and goes for a while and after than it is empty but column B continues for a while. This has the effect that if I use the code below:

sh = app.Workbooks.get_Item("Workbook1.xlsx").Worksheets.get_Item("Sheet1");
fullRow = sh.Rows.Count;
lastRow = sh.Cells[fullRow, 1].End(Excel.XlDirection.xlUp).Row;

I get as last row the last row that has B non empty. Which might be even 50 rows below the place where A starts being null. Is there a way to do it with C# without iterating over all values?

EDIT

It turns out that Column A is based on column C so I should check for C. As it turns out C is yielding the same result with A maybe because of the function. Luckily there is a column D that does not have the same issue so if I use the code above changing 1 for 4 it works likes a charm.

1
Is sh.Cells zero-based, i.e., can you do sh.Cells[fullRow, 0]? I don't think so, but worth checking. - Doug Glancy
your code is ok for what you need. The only possibility I could think of, which gives you this result, is if you have any formulas in 'empty' cells in column A. These could be formulas which return empty string, like ="". - Kazimierz Jawor
@DougGlancy I have already tired that and it throws an exception. - idipous
@KazJaw I will check for it but I a pretty sure it does have any formulas. - idipous
@idipous, in other words, try to check it manually in your excel file, with ctrl+arrows, where movement will stop. then analyse the content of cells. - Kazimierz Jawor

1 Answers

1
votes

EDIT: Sorry, I initially misunderstood the question, thanks KekuSemau for clearing that up!

Try:

sh.Range["A1", sh.Cells[1,sh.Rows.Count]].End(Excel.XlDirection.xlDown).Value;

Also, if you know there will be no empty cells in the column you could use CountA:

var usedRows = xlApp.WorksheetFunction.CountA(xlWorkSheet.Columns[1]);

Source