For a richtextbox how can I count all the characters on a current line?
Printable View
For a richtextbox how can I count all the characters on a current line?
Code:Option Explicit
Private Const EM_LINEINDEX = &HBB
Private Const EM_LINELENGTH = &HC1
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Sub Form_Load()
Dim s As String
s = "First" & vbNewLine & "Second Line" & vbNewLine & _
"A much longer line"
Rich.Text = s
Debug.Print LineLength(1) '==> 5
End Sub
Private Function LineLength(Line As Long) As Long
'note Rich line numbers are zero based
Dim FC As Long 'first character position of the specified line (also zero based)
FC = SendMessage(Rich.hwnd, EM_LINEINDEX, Line - 1, ByVal 0&)
LineLength = SendMessage(Rich.hwnd, EM_LINELENGTH, FC, ByVal 0&)
End Function
You didn't specify what you meant by "on a current line".
This returns the char count (including spaces) of all the text. If you want just one line you're going to have to specify what constitutes a line, as in user selected text.
Code:MsgBox Len(RichTextBox1.Text)
GDO, try like this
check and feedback.Code:Dim lBegin As Long, lEnd As Long
Dim CurPos As Long
With RichTextBox1
CurPos = .SelStart
If CurPos = 0 Then CurPos = 1
'Find line begin and end
lBegin = InStrRev(.Text, vbCrLf, CurPos)
lEnd = InStr(CurPos, .Text, vbCrLf)
If lBegin = 0 Then lBegin = -1
If lEnd = 0 Then
lEnd = Len(.Text) - 1
Else
lEnd = lEnd - 2
End If
MsgBox "Chr Count of Current line " & lEnd - lBegin
End With
RTB's don't really have lines, they have paragraphs. A "line" is based on whether wrapping is on, which scrollbar settings you have, etc.
What the heck do you really mean by "line" anyway? You can't look for CR or CRLF, since those are paragraph delimiters.
this is true.Quote:
You can't look for CR or CRLF, since those are paragraph delimiters.
hope this one works even if there is no CR or CRLF, try and feed back
edited: this line of code missed "CurPos = .SelStart" , now addedCode:Option Explicit
Private Sub Command1_Click()
Dim CurLine As Integer, Sline As Integer, Fline As Integer
Dim CurPos As Integer, Spos As Integer, Epos As Integer
Dim ChrCnt As Integer
Dim Txt As String
With RichTextBox1
CurPos = .SelStart
CurLine = .GetLineFromChar(CurPos)
Spos = CurPos
Do
Spos = Spos - 1
If Spos < 0 Then Exit Do 'in case of first line
.SelStart = Spos
Sline = .GetLineFromChar(Spos)
Loop Until Not Sline = CurLine 'loop up to the line
Spos = Spos + 1 'start position
If Spos < 0 Then Spos = 0
Epos = CurPos
Do
Epos = Epos + 1
If Epos > Len(RichTextBox1) Then Exit Do 'in case of last line
.SelStart = Epos
Fline = .GetLineFromChar(Epos)
Loop Until Not Fline = CurLine 'loop up to the line
.SelStart = Spos
.SelLength = Epos - Spos
Txt = Replace(.SelText, vbCrLf, "") 'remove crlf if any
ChrCnt = Len(Txt)
.SelStart = CurPos
End With
MsgBox "Current line = " & Txt & vbNewLine & "Chr Count = " & ChrCnt
End Sub