Conversion to proper case

Conversion to proper case

When dealing with proper names, you may want to capitalize the first letter of each word, e.g. convert “john smith” into “John Smith”. Under VB3 you had to write a custom function to do the job, whereas VB4 has introduced the versatile StrConv routine, that does it with just one statement:

properName = StrConv(text, vbProperCase)

However, you should be aware that this variant of StrConv also forces a conversion to lower case for all the characters that are not at the beginning of a word. In other word, “seattle, USA” is converted to “Seattle, Usa”, which might not be desirable. Therefore you still need a custom routine, but you can take advantage of StrConv capabilities to reduce the amount of code you need:

Function ProperCase(text As String) As String    Dim i As Integer    ' prepare the result    ProperCase = StrConv(text, vbProperCase)    ' restore all those characters that were capitalized    For i = 1 To Len(text)        Select Case Asc(Mid$(text, i, 1))            Case 65 To 90   ' A-Z                Mid$(ProperCase, i, 1) = Mid$(text, i, 1)        End Select    NextEnd Function


Share the Post: