XTreme Logo

If you appreciate these tips, please consider a small donation:

General Tip - Intermediate

Reading the lines of a multiline textbox into the an array.

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This code will read the individual lines out of a
' Multi-Line TextBox and copy them into an array.
' This code does not care if each line in the Multi-Line
' TextBox is terminated.
'
' To use this code, place a TextBox on a Form,
' Set the Multi-Line property to True, and place
' into the Text property several lines of text.
' Then copy the entire sample and paste it into
' the General Declarations code window of the Form.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''


' Declare Form level Array to store the results.
Dim strArray() As String

' Declare Constants for use with API's.
Const EM_GETLINECOUNT = &HBA
Const EM_LINELENGTH = &HC1
Const EM_LINEINDEX = &HBB

' Declare API call.
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()
   ' Declare local variables to keep track of cursor.
    Dim intLineStart As Integer
    Dim intLineLength As Integer
    Dim lRet As Long
   ' Initialize the Array.
    ReDim strArray(1)
   ' Loop until all lines in the text box have been read.
    For lRet = SendMessage(Text1.hwnd, EM_GETLINECOUNT, _
                          0&, 0&) To 1 Step -1
       ' Set cursor to next line to read.
        Text1.SelStart = intLineStart
        ' Determine the length of this line.
        intLineLength = SendMessage(Text1.hwnd, _
                        EM_LINELENGTH, Text1.SelStart, 0&)
        ' Select the text of this line.
        Text1.SelLength = intLineLength
        ' Copy the selected text into the Array at the
        ' appropriate index
.
        strArray(UBound(strArray) - 1) = Text1.SelText
        ' Increase the size of the Array to handle
        ' the next line.

        ReDim Preserve strArray(UBound(strArray) + 1)
        ' Set the line counter to point at the next line
        intLineStart = intLineStart + intLineLength
    Next
    ' This code is just for troubleshooting and
   
' proving the array contains the info from the TextBox
    Dim x As Long
    For x = 0 To UBound(strArray) - 1
        Debug.Print strArray(x)
    Next
    Debug.Print "Done"
End Sub





[ Back To The Top ]

Contact: web@xtremecomp.com
All contents copyright XTreme Computing unless noted otherwise.