Solved

Count Lines in a Text Box

Posted on 1997-12-28
17
481 Views
Last Modified: 2008-02-26
Hi,
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
Do
pos = InStr(pos + 1, text1, Chr$(13))
n = n + 1
Loop Until pos = 0
text2 = n

MailTo:Tablet@ix.netcom.com
0
Comment
Question by:Jambyte
  • 5
  • 5
  • 3
  • +3
17 Comments
 
LVL 5

Expert Comment

by:cekman
ID: 1963762
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
CEkman
0
 
LVL 17

Expert Comment

by:ramrom
ID: 1963763
I have an answer. Unlock the question and I'll post it.
0
 
LVL 9

Expert Comment

by:cymbolic
ID: 1963764
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.
0
 
LVL 2

Author Comment

by:Jambyte
ID: 1963765
he hasn't answered for a while... go ahead!
0
 
LVL 9

Expert Comment

by:cymbolic
ID: 1963766
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
Public Const EM_GETLINECOUNT = &HBA

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)
 nlines&=SendMessage(hndl,EM_GETLINECOUNT,0,0&)
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
Public Const EM_GETFIRSTVISIBLELINE = &HCE
 'get a line
Public Const EM_GETLINE = &HC4
...and more...

I hope I haven't fumble fingered any of this in.  God luck!
0
 
LVL 9

Expert Comment

by:cymbolic
ID: 1963767
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

Public Const EM_GETLINECOUNT = &HBA


'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




 
0
 
LVL 2

Author Comment

by:Jambyte
ID: 1963768
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"

0
 

Expert Comment

by:macikgoz
ID: 1963769
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.
0
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 
LVL 2

Author Comment

by:Jambyte
ID: 1963770
Im using access 97

0
 
LVL 9

Expert Comment

by:cymbolic
ID: 1963771
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.
0
 
LVL 9

Expert Comment

by:cymbolic
ID: 1963772
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.
0
 

Expert Comment

by:noconnor
ID: 1963773
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!

0
 
LVL 17

Expert Comment

by:ramrom
ID: 1963774
I have tried that and it works.
0
 
LVL 2

Author Comment

by:Jambyte
ID: 1963775
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?

0
 

Accepted Solution

by:
noconnor earned 20 total points
ID: 1963776
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
    Ctrl1.SetFocus
    SendKeys "{F2}"
    SendKeys "^{HOME}"
    NoLines = 0
    LastLen = 0
    Do
        'move selection down a line
        SendKeys "+{DOWN}"
        DoEvents
        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.
0
 
LVL 2

Author Comment

by:Jambyte
ID: 1963777
could you explain a little more on how i apply that code?

0
 

Expert Comment

by:noconnor
ID: 1963778
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.

0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

It took me quite some time to sort out all the different properties of combo and list boxes available from Visual Basic at run-time. Not that the documentation is lacking: the help pages are quite thorough and well written. The problem was rather wh…
Today's users almost expect this to happen in all search boxes. After all, if their favourite search engine juggles with tens of thousand keywords while they type, and suggests matching phrases on the fly, why shouldn't they expect the same from you…
Familiarize people with the process of utilizing SQL Server views from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Access…
In Microsoft Access, learn how to “cascade” or have the displayed data of one combo control depend upon what’s entered in another. Base the dependent combo on a query for its row source: Add a reference to the first combo on the form as criteria i…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now