Want Enter to put CR in Textbox (not just CTRL-Enter)

G

Guest

I'm using a form with VBA and the form has several text boxes. When entering
information I need to be able to put carriage return/line feeds into the
text. However just hitting the Enter key causes the next field in the form
to become active (leaving the field that I was editing) - like TAB does. If
I want carriage return/line feed I have to type CTRL-Enter. Is there a way
to cause carriage return/line feeds to be put into a form text box using just
the Enter key? This may seem like a small thing but others use this form too
and hitting just Enter (for CR/LF) is a hard habit to break.

Thanks,
Will
 
P

Peter T

Hi Will,

Bit tricky to get vbCrLf inserted in correct position and re-setting the
cursor position if Enter is pressed in the middle of the text. Anyway have a
go with this and see how you get on

Private Declare Function GetKeyState32 Lib "user32" _
Alias "GetKeyState" (ByVal vKey As Integer) As Integer

Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
Dim i As Long, n As Long, cnt As Long
Dim nSelPos As Long
Dim sText As String
Dim by() As Byte

If GetKeyState32(vbKeyReturn) < 0 Then '-128, enter pressed

Cancel = True ' abort update
nSelPos = TextBox1.SelStart 'cursor pos
sText = TextBox1.Text

If Len(sText) Then
' problem: vbCrLf is two characters but seems
' .SelStart does not count the Cr character
' need to count no. of Chr(13)'s before cursor
' for each chr(13) need to add an extra character count
' left of cursor, complicated 'cos need to increase length
' of the left portion of the string during the search.
' Could use Instr but I like this byte array approach!

by = sText
n = nSelPos * 2 - 1
Do While i <= n
If by(i) = 13 Then
n = n + 2
cnt = cnt + 1
End If
i = i + 1 ' 2 bytes/char, interested in every other byte
Loop

End If

sText = Left(sText, nSelPos + cnt) & _
vbCrLf & _
Mid(sText, nSelPos + 1 + cnt, Len(sText))
TextBox1.Text = sText
TextBox1.SelStart = nSelPos + 1
End If

End Sub

Don't forget to set MultiLine & WordWrap prop's to True

Regards,
Peter T
 
P

Peter T

:), in a gritted teeth kind of way!

Silly really, I knew about EnterKeyBehavior and even have it in one of my
app's, but forgot...

Regards,
Peter T
 
G

Guest

Thanks a bunch - it worked great! And a little levity during the work day is
always appreciated, Peter.
Will
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top