/ Published in: Visual Basic
Using VBA (Visual Basic for Applications) in MS Access, I needed to convert TitleCase to lower\_case, but did not have the regex enqine that's available in VB Script. This solution, based on a simple state machine model, splits the words in the string (converting to lower-case is trivial after that). It treats a block of upper-case letters as a single word, but the last letter of that block is the first letter of the next word; e.g., "VBAIsLame" becomes "VBA Is Lame". Because of this behaviour, if you subsequently convert to lower-case, you cannot reliably convert back to the original (all-upper-case words are indistinguishable from title-case words). To resolve this potential ambiguity, you can supply an "upper\_case\_indicator" that will be inserted before each capital letter that isn't the start of a word. So `TitleCaseSplit("VBAIsLame", "_", "-")` returns "V-B-A\_Is\_Lame".
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
Private Function TitleCaseSplit(str As String, Optional delim As String = " ", Optional upper_case_indicator As String = "") As String Dim chr As String, out As String Dim state As String Dim i As Integer Dim is_upper As Boolean chr = Mid(str, 1, 1) out = chr state = "first character" For i = 2 To Len(str) chr = Mid(str, i, 1) is_upper = StrComp(chr, LCase(chr), vbBinaryCompare) Select Case state Case "first character" If is_upper Then state = "upper-case word" Else state = "title-case word" End If out = out & chr Case "title-case word" If is_upper Then state = "first character" out = out & delim & chr Else out = out & chr End If Case "upper-case word" If is_upper Then out = Left(out, Len(out) - 1) & upper_case_indicator & Right(out, 1) & chr Else state = "title-case word" out = Left(out, Len(out) - 1) & delim & Right(out, 1) & chr End If End Select Next TitleCaseSplit = out End Function