View Full Version : vbSentenceCase -> Convert a string to Sentence Case


RossWindows
04-16-2008, 03:22 PM
I've seen quite a few people searching for this function, so I figured I'd post this code here for everybody.

This code will convert a text string to what is essentially a vbSentenceCase.
Why Microsoft didn't add this to the strConv function in the first place, I don't know, but here it is. I've modified it a bit to work in my particular application.

Credit goes to KDg

Private Sub MyControl_AfterUpdate()
On Error GoTo MyControl_After_Update

Dim x, y As Integer, vbSentenceCase As Long

vbSentenceCase = Len(Me![MyControl])

x = 1
Do Until StrComp(Mid(Me![MyControl], x, 1), Chr(32)) <> 0
x = x + 1
Loop
Me![MyControl] = Left(Me![MyControl], x - 1) & UCase(Mid(Me![MyControl], x, 1)) & Right(Me![MyControl], vbSentenceCase - x)

Do While x < vbSentenceCase
If InStr(x, Me![MyControl], ".") Then
x = InStr(x, Me![MyControl], ".")
y = 1
Do Until StrComp(Mid(Me![MyControl], x + y, 1), Chr(32)) <> 0
y = y + 1
Loop
Me![MyControl] = Left(Me![MyControl], x + y - 1) & UCase(Mid(Me![MyControl], x + y, 1)) & Right(Me![MyControl], vbSentenceCase - x - y)
End If
y = 0
x = x + 1
Loop

MyControl_After_Update:

End Sub

The original code created by KDg is:

Dim x As Integer
Dim y As Integer
Dim lngLenMem As Long

lngLenMem = Len(Me.txtMemo)
'little loop to Cap first letter

x = 1
Do Until StrComp(Mid(Me.txtMemo, x, 1), Chr(32)) &lt;&gt; 0
x = x + 1
Loop
Me.txtMemo = Left(Me.txtMemo, x - 1) & UCase(Mid(Me.txtMemo, x, 1)) & Right(Me.txtMemo, lngLenMem - x)


On Error GoTo Oops
Do While x &lt; lngLenMem
If InStr(x, Me.txtMemo, ".") Then
x = InStr(x, Me.txtMemo, ".")
y = 1
Do Until StrComp(Mid(Me.txtMemo, x + y, 1), Chr(32)) &lt;&gt; 0
y = y + 1
Loop
Me.txtMemo = Left(Me.txtMemo, x + y - 1) & UCase(Mid(Me.txtMemo, x + y, 1)) & Right(Me.txtMemo, lngLenMem - x - y)
End If
y = 0
x = x + 1
Loop

Oops:
'probably the end of the memo field causing and error, time to forget it
End Sub

Thank you KDg!