I was having a recent discussion with a fellow MVP and came across a function I developed a while back and thought it could be useful to others. Below is a very simple function which uses a RegEx pattern to break apart a Came Case string into a legible string.
'---------------------------------------------------------------------------------------
' Procedure : RegEx_SplitCamelCase
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Split/Break a Camel Case string
' Copyright : The following may be altered and reused as you wish so long as the
' copyright notice is left unchanged (including Author, Website and
' Copyright). It may not be sold/resold or reposted on other sites (links
' back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sString : Camel Case string to break/split
' sDelim : Character to use as a spcaer, if omitted will use a space
'
' Usage:
' ~~~~~~
' ? RegEx_SplitCamelCase("SplitCamelCase")
' Returns Split Camel Case
' ? RegEx_SplitCamelCase("SplitCamelCase", "_")
' Returns Split_Camel_Case
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2008-05-03 Initial Release
' 2 2022-11-16 Update Function name
' Update Error Handler
'---------------------------------------------------------------------------------------
Public Function RegEx_SplitCamelCase(sString As String, Optional sDelim As String = " ") As String
On Error GoTo Error_Handler
Dim oRegEx As Object
Set oRegEx = CreateObject("VBScript.RegExp")
With oRegEx
.Pattern = "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))"
.Global = True
RegEx_SplitCamelCase = .Replace(sString, "$1" & sDelim)
End With
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_SplitCamelCase" & 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
This is fantastic. was needing a way to convert from camel to snake.
Brilliant! Thanks so much for sharing this.
This is interestingly wonderful. I have tested it and it worked like magic.