VBA – Convert a String to Camel Case

Smiling Camel

Previously, I published an article on Splitting a Camel Case String back to plain English:

Today, I thought it a good idea to publish the code to do the inverse, that is to take a normal string and convert it to Camel Case.

Camel Case using Basic String Functions

The code is very straight forward:

  1. Convert the specified delimiter to a space
  2. Use the StrConv function to capitalize the 1st letter of each word
  3. Remove all the space
  4. Return the result

Thus, you end up with a function like:

'---------------------------------------------------------------------------------------
' Procedure : MakeCamelCase
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Converts a string to CamelCase
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: None required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sInput    : String to convert
' sDelim    : Character to use as a the delimiter for Capitalization,
'               if omitted will use a space
'
' Usage:
' ~~~~~~
' ?MakeCamelCase("Make Camel Case")
'       Returns MakeCamelCase
' ?MakeCamelCase("Make Camel_Case", "_")
'       Returns MakeCamelCase
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2022-11-09              Imitial Public Release
'---------------------------------------------------------------------------------------
Function MakeCamelCase(ByVal sInput As String, Optional sDelim As String = " ") As String
    On Error GoTo Error_Handler
    Dim sOutput             As String
    
    sOutput = sInput
    If sDelim <> " " Then sOutput = Replace(sOutput, sDelim, " ")
    sOutput = StrConv(sOutput, vbProperCase)
    sOutput = Replace(sOutput, " ", "")
    MakeCamelCase = sOutput
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
        "Error Source: MakeCamelCase" & vbCrLf & _
        "Error Number: " & Err.Number & vbCrLf & _
        "Error Description: " & Err.Description & _
        Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
        , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

Usage Examples

Below are a couple examples of how it can be used.

Example 1

Debug.Print MakeCamelCase("This is just a simple test")

would return:

ThisIsJustASimpleTest

Example 2

Debug.Print MakeCamelCase("Please-make-This-Camel-cased", "-")

would return

PleaseMakeThisCamelCased

Camel Case Using RegEx Patterns

The above works just fine for plain test string with a singular delimiter like a space. That said, I had a need to have a more ‘adaptive’ function that could recognize a variety of delimiters in the same string and thus I turned towards RegEx patterns to do the job. This is what I came up with:

'---------------------------------------------------------------------------------------
' Procedure : RegEx_MakeCamelCase
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Converts a string to CamelCase using RegEx pattern matching
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: None required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sInput    : String to convert
'
' Usage:
' ~~~~~~
' ?RegEx_MakeCamelCase("Make Camel Case")
'       Returns -> MakeCamelCase
' ?RegEx_MakeCamelCase("Make Camel_Case")
'       Returns -> MakeCamelCase
' ?RegEx_MakeCamelCase("Make~Camel_Case PleASe")
'       Returns -> MakeCamelCasePlease
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2022-11-16              Imitial Public Release
'---------------------------------------------------------------------------------------
Public Function RegEx_MakeCamelCase(sInput As String) As String
    On Error GoTo Error_Handler
    Dim oRegEx          As Object
    Dim sOutput             As String

    Set oRegEx = CreateObject("VBScript.RegExp")
    With oRegEx
        .Global = True
        .IgnoreCase = False    'Search should be case-sensitive
        .MultiLine = True
        .Pattern = "[_;\\\\/:*?\""<>|&'~-]" 'Characters to replace
        sOutput = .Replace(sInput, " ")
    End With
    
    sOutput = StrConv(sOutput, vbProperCase)
    sOutput = Replace(sOutput, " ", "")
    RegEx_MakeCamelCase = sOutput

Error_Handler_Exit:
    On Error Resume Next
    Set oRegEx = Nothing
    Exit Function

Error_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
        "Error Source: RegEx_MakeCamelCase" & vbCrLf & _
        "Error Number: " & Err.Number & vbCrLf & _
        "Error Description: " & Err.Description & _
        Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
        , vbOKOnly + vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

The beauty here is the characters to use as delimiters can easily be adjusted, by altering the .Pattern as required, depending on your usage scenario.

For instance, if we didn’t want to explicitly specify each character to use as a delimiter and instead wanted to delimit on any non-alphanumeric character we could simply use a .Pattern like:

.Pattern = "[^a-zA-Z\d\u00C0-\u00FF]"

and now we have a completely autonomous function for creating Camel Case strings.

Usage Examples

Below are a couple examples of how it can be used.

Example 1

Debug.Print RegEx_MakeCamelCase("Make Camel Case")

would return:

MakeCamelCase

Example 2

Debug.Print RegEx_MakeCamelCase("Please-mAke_This:Camel~cased")

would return

PleaseMakeThisCamelCased

Comparison

As a point of comparison, if we retake the last usage example and test the 1st function you will immediately see where it falls short for more advance use cases.

Debug.Print MakeCamelCase("Please-mAke_This:Camel~cased")

would return

Please-make_this:camel~cased

So I hope you can see the usefulness of RegEx in handling such cases.

If you are certain to only have a single identifiable delimiter, the 1st function is the way to go as it will necessarily perform faster, but if you may have a varying set of delimiters or want a more robust/versatile function then RegEx is the solution! The choice is yours.

Database Cleanup

Part of the reason I developed such a function was to be able to cleanup naming within a database. For instance, you could do something like the following to cleanup all the table field names in one go:

Sub FixTableFieldNames()
    Dim db As DAO.Database
    Dim tdf As DAO.TableDef
    Dim fld As DAO.Field
    
    Set db = CurrentDb
    For Each tdf In db.TableDefs
        For Each fld In tdf.Fields
            If fld.Name <> RegEx_MakeCamelCase(fld.Name) Then
                Debug.Print "Updating " & tdf.Name, fld.Name, , , RegEx_MakeCamelCase(fld.Name)
                fld.Name = RegEx_MakeCamelCase(fld.Name)
            End If
        Next fld
    Next
    
    Set fld = Nothing
    Set tdf = Nothing
    Set db = Nothing
End Sub

This will remove special characters and properly Camel Case the field names.

Just one of many possible uses.

Resources on the Subject