2

I have the following code:

Excel.Range range = workSheet.UsedRange;
for (rowCount = 2; rowCount <= range.Rows.Count; rowCount++)
  {
     //Do something here
  }

However, I encounter the following problem. If I have the following excel data:

cell1, cell2, cell3

cell4, cell5, cell6

..............cell7

range.Rows.Count will return 3. However, I don't care about column C - it has some data that is used for drop-down lists within say column 1. How can I get the range.Rows.Count only for columns A and B?

For example: enter image description here

1
  • Can you post a screenshot and be clear about what you want to count and what you want to ignore? Commented Aug 23, 2011 at 16:08

1 Answer 1

1

Assuming there are no blanks in column A, just walk down rows until you hit a blank row using range.Offset(x,y): (sorry, I'm more fluent with Excel VBA, you'll have to translate to C#)

Dim myCell as Range
set myCell = workSheet.Range("A2");
Do Until myCell.Formula = ""
     'Do something here
     set myCell = myCell.Offset(1,0) 'Moves down a row 
Loop

Or just loop through numerically using Worksheet.Cells(row,col):

Dim myRow as Integer
myRow = 2
Do Until cells(myrow,2).Formula = ""
     'Do something here
     myRow = myRow + 1
Loop

Edit: You could also use Range("A1").End(xlDown) to find the last populated cell of the first column. This should work with your current logic. Something like (I'll try it in C#):

Excel.Range range = workSheet.Range("A1", Range("A1").End(xlDown));
for (rowCount = 2; rowCount <= range.Rows.Count; rowCount++)
  {
     //Do something here
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.