Count Lines in a Text Box

how can i count the # of lines in a text box?
i got this much, but it only counts the # of CR's. any help would be great!
Dim n As Long
Dim pos As Long
n = 0
pos = 0
pos = InStr(pos + 1, text1, Chr$(13))
n = n + 1
Loop Until pos = 0
text2 = n
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

I don't understand how you can count the number of lines in a box other than by counting the carriage returns or the sentences (periods). The actual text box size can always vary, and the number of letters that fit in the box will also vary depending on letters typed and whether they are upper or lower case.

Also - people with different resolutions will also get different results.

How do you propose to distinguish a 'line'. If you had to guess you could determine the average number of characters that fit on a line - get the length of the text box using the LEN function and divide LEN/averagecharactersperline = approximate number of lines.

Hope this helps
ramromconsultant Commented:
I have an answer. Unlock the question and I'll post it.
Actually, I can provide three methods for counting lines in a text box, but all require you to use the WIN32API.  Text boxes are known to Windows more generally as multiline edit controls. These controls retain information internally regarding where soft line breaks occur. A hard line break would be a CRLF sequence inserted by you.  Soft line breaks are retained by the insertion of CRCRLF sequences, that do not come back to you using the .text property.  However, by sending a particular text formatting message to the  control, you can retrieve those formaatting characters fro your own internal counting purposes.  Also, (and easir) there is an api call that returns a line count, and with some additional programming you can also get a visible line count.  But I do not want to steal ramrom's answer, so I'll wait on him.
Newly released Acronis True Image 2019

In announcing the release of the 15th Anniversary Edition of Acronis True Image 2019, the company revealed that its artificial intelligence-based anti-ransomware technology – stopped more than 200,000 ransomware attacks on 150,000 customers last year.

JambyteAuthor Commented:
he hasn't answered for a while... go ahead!
Multiline edit controls can be thought of as a single string. You set and retrieve this string using the .text property in VB.  However,  Windows provides a set of edit control messages that makes it possible to treat the text as a series of lines instead of a single string.  One message returns the number of lines in the control.

For instance, to get the number of lines in a control, declare the following function and constant:

Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

then retrieve the number of lines thusly from a Text1 control:

 txtlines&=nlines&(text1.Hwnd) 'Windows works off control handles, so pass it

using a function like the following:

private function nlines&(hndl)
end function

Following constants (plus others) are also interesting:
 'tell windows to return soft carriage returns as well as hard
Public Const EM_FMTLINES = &HC8
 'get number of first visible line
 'get a line
Public Const EM_GETLINE = &HC4
...and more...

I hope I haven't fumble fingered any of this in.  God luck!
Sorry, I did fumble finger it in.  This is better:

Place the following API declare code into the general declarations area of a bas module:

Public Declare Function SendMessageLong Lib "user32" Alias "SendMessageA" _
    (ByVal hwnd As Long, _
     ByVal wMsg As Long, _
     ByVal wParam As Long, _
     ByVal lParam As Long) As Long


'Calling the API from the textbox change event:
Sub Text1_Change()

    Dim lineCount&
    On Local Error Resume Next
   'get the number of lines in the edit control
    lineCount& = SendMessageLong(Text1.hwnd, EM_GETLINECOUNT, 0&, 0&)
    lblLineCount = Format$(lineCount&, "##,###")

End Sub

JambyteAuthor Commented:
What sould i save the module as? i have tried a lot of differn't names and i allways get the same error,
"methiod or data member not found' and it highlights ".hwnd"

Are you talking about Visual Basic 4.0/5.0 or MS Access ???

The Visual Basic text and list controls are subclassed off of standard Windows controls and therefore respond correctly to most of the messages for these controls. They allow to be passed by their handles but what about Access text box controls? Surely, they are not the same as in VB.
JambyteAuthor Commented:
Im using access 97

My mistake.  Access 97 controls does not seem to have an hWnd property, therefore you can not use the SendMessage API to count lines.  Please reject my answer.
My mistake.  Access 97 controls does not seem to have an hWnd property, therefore you can not use the SendMessage API to count lines.  Please reject my answer.
One very grubby way to do it would be to send keystrokes to the text box (SendKeys command) to step through each lines with Shift+Down Arrow.  Each time, check the current selection (SelText or SelLength) - when the selection hasn't changed, you've reached the end.

I haven't tried this, but it could work.  Not very elegant, though!

ramromconsultant Commented:
I have tried that and it works.
JambyteAuthor Commented:
could you guys explain a little bit more on that. i got the sendkeys part, what should i put in the code that will return a value if it has found a new line?

Declare this function in a module:

Public Function CountLines(Ctrl1 As TextBox) As Integer

    Dim NoLines As Integer, Done As Boolean
    Dim CurLen As Integer, LastLen As Integer
    'give focus to control and move to beginning
    SendKeys "{F2}"
    SendKeys "^{HOME}"
    NoLines = 0
    LastLen = 0
        'move selection down a line
        SendKeys "+{DOWN}"
        CurLen = Ctrl1.SelLength
        'check length of selection against last time (if no change, we're at end)
        Done = True
        If CurLen > LastLen Then
            'more has been added to selection, so there's still some lines left
            NoLines = NoLines + 1
            LastLen = CurLen
            Done = False
        End If
    Loop Until Done
    CountLines = NoLines
End Function

On your form, pass it a TextBox control, and it will return the number of lines, eg:

    NumLines = CountLines(Me.Text0)

Hope this is OK.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
JambyteAuthor Commented:
could you explain a little more on how i apply that code?

Create a module in your Access database.  Paste the first part of my answer (from Public Function ... to End Function) into that module and save it.

Then, if you've got a text box on your form called 'Text1', for example, then somewhere in the code for your form (eg. in the code behind a button), type MsgBox CountLines(Me.Text1).  This will pop up a message telling you the number of lines in your text box.  As CountLines is a public function, you can call it from any form, and you can assign its result to a variable (as in the second part of my answer), or put the result in another text box on your form.

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Access

From novice to tech pro — start learning today.