VB and VBA Users Source Code: Preventing specific lines in a textbox from being edited
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Preventing specific lines in a textbox from being edited
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Wednesday, January 30, 2002
Hits:
735
Category:
Windows API
Article:
The following code shows you how to prevent specific lines in a textbox from being edited by the user. Option Explicit 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 'Purpose : Prevents users from editing specific lines in a MultiLine textbox 'Inputs : txtProtect The textbox being edited ' KeyAscii The Ascii value of the KeyPressed (from the KeyPress event of the textbox) ' avLinesToProtect The list of lines to protect 'Outputs : Returns the icon 'Author : Andrew Baker (copyright www.vbusers.com) 'Date : 08/01/2001 20:24 'Notes : 'Example : Below is an example of how to use this function (place in form containing a multiline textbox): 'Private Sub Form_Load() ' Text1.Text = "This Line is PROTECTED!!!" & vbNewLine & "This Line is PROTECTED!!!" & vbNewLine & "This Line is PROTECTED!!!" & vbNewLine & "This Line in NOT PROTECTED" 'End Sub 'Private Sub Text1_KeyPress(KeyAscii As Integer) ' KeyAscii = TextBoxProtectLines(Text1, KeyAscii, 1, 2, 3) 'Protect first three lines 'End Sub 'Revisions : Function TextBoxProtectLines(txtProtect As TextBox, KeyAscii As Integer, ParamArray avLinesToProtect()) As Integer Dim lStartLine As Long, lEndLine As Long Dim sLinesToProtect As String Const EM_LINEFROMCHAR = &HC9 On Error GoTo ErrFailed 'Return the KeyAscii value TextBoxProtectLines = KeyAscii 'Determine the current line/s the user is editing lStartLine = SendMessage(txtProtect.hwnd, EM_LINEFROMCHAR, txtProtect.SelStart, 0&) + 1 lEndLine = SendMessage(txtProtect.hwnd, EM_LINEFROMCHAR, txtProtect.SelStart + txtProtect.SelLength, 0&) + 1 sLinesToProtect = Join(avLinesToProtect, "|") 'split the forbidden string into an array If Len(sLinesToProtect) Then sLinesToProtect = "|" & sLinesToProtect If InStr(1, sLinesToProtect, "|" & lStartLine) > 0 Or InStr(1, sLinesToProtect, "|" & lEndLine) > 0 Then 'User is trying to edit a protected line, return an empty ascii value TextBoxProtectLines = 0 End If End If Exit Function ErrFailed: Debug.Print "Error in TextBoxProtectLines: " & Err.Description On Error GoTo 0 End Function
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder