# Excel: Count Lines in a Cell

30 Nov 2017Recently I was using an Excel spreadsheet to prepare some data and I had a constraint to work to in the number of lines of data the target system could display. Unfortunately rather than rows of data in Excel this was to match against rows of data in a single Excel cell. So the question is, how can you count the number of rows in an Excel cell?

# The Algorithm

There was no inbuilt function I could find for getting this information, and whilst I could write a quick VBA function to return a value I like to try and avoid macro enabling spreadsheets wherever possible. There are always discussions about security and enabling the code whenever you share it with someone; something I’d rather not spend my time on. Therefore to address this I came up with a somwehat quick and dirty approach using inbuilt functions.

The first step was to count how many characters there are in a cell. This can be achieved using the LEN function.

```
=LEN(A2)
```

Next I removed all of the line feed characters (ASCII value 10) in the cell, by replacing them with nothing; and counted the number of characters again. Excel registers line feeds as additional characters and as markers for a newline. Curiously Windows uses carriage return + line feed for new lines, but replacing the carriage return (ASCII value 13) made no difference to the character count.

```
=LEN(SUBSTITUTE(A2,CHAR(10),""))
```

Then by taking the difference of the two I can tell how many new lines are in the cell.

```
=B2-C2
```

Finally if there is content in the cell then there must be at least one line not ending in a newline and if there isn’t then there would be no lines. We can therefore check the length and add one if we have at least some content present.

```
=D2+IF(LEN(A2)>0,1,0)
```

# Combining it

Taking all of the elements together and using an example of cell A2, we can then produce the following combination of in-built functions to count the number of lines of text in a cell.

```
=LEN(A2)-LEN(SUBSTITUTE(A2,CHAR(10),""))+IF(LEN(A2)>0,1,0)
```