VBA キャメルケース スネークケース ケバブケース 変換
概要
キャメルケースとスネークケースを変換するメソッド
コード
' キャメルケースに変換
Private Function toCamel(ByVal val As String, delimiter As String, Optional ByVal isFirstUpper As Boolean = False) As String
Dim ret As String
Dim i As Long
Dim snakeSplit As Variant
snakeSplit = Split(val, delimiter)
For i = LBound(snakeSplit) To UBound(snakeSplit)
ret = ret & UCase(Mid(snakeSplit(i), 1, 1)) & _
LCase(Mid(snakeSplit(i), 2, Len(snakeSplit(i))) _
)
Next
If isFirstUpper Then
toCamel = ret
Else
toCamel = LCase(Mid(ret, 1, 1)) & Mid(ret, 2, Len(ret))
End If
End Function
'スネークケースをキャメルケースに変換
Public Function snakeToCamel(ByVal val As String, Optional ByVal isFirstUpper As Boolean = False) As String
snakeToCamel = toCamel(val, "_", isFirstUpper)
End Function
'ケバブケースをキャメルケースに変換
Public Function kababuToCamel(ByVal val As String, Optional ByVal isFirstUpper As Boolean = False) As String
kababuToCamel = toCamel(val, "-", isFirstUpper)
End Function
'キャメルケースをスネークケースに変換
' Public Function camelToSnake(ByVal val As String, delimiter As String, Optional ByVal isUpper As Boolean = False) As String
'キャメルケースから変換
Private Function fromCamel(ByVal val As String, delimiter As String, Optional ByVal isUpper As Boolean = False) As String
Dim ret As String
Dim i As Long
Dim length As Long
length = Len(val)
For i = 1 To length
If UCase(Mid(val, i, 1)) = Mid(val, i, 1) Then
' 大文字
If i = 1 Then
' 最初の文字なら、区切り文字は付与しない
ret = ret & Mid(val, i, 1)
ElseIf i > 1 And UCase(Mid(val, i - 1, 1)) = Mid(val, i - 1, 1) Then
' 前の文字が大文字なら、区切り文字は付与しない
ret = ret & Mid(val, i, 1)
Else
' 小文字なので区切り文字を付与
ret = ret & delimiter & Mid(val, i, 1)
End If
Else
' 小文字
ret = ret & Mid(val, i, 1)
End If
Next
If isUpper Then
fromCamel = UCase(ret)
Else
fromCamel = LCase(ret)
End If
End Function
'キャメルケースをスネークケースに変換
Public Function camelToSnake(ByVal val As String, Optional ByVal isUpper As Boolean = False) As String
camelToSnake = fromCamel(val, "_", isUpper)
End Function
'キャメルケースをケバブケースに変換
Public Function camelToKababu(ByVal val As String, Optional ByVal isUpper As Boolean = False) As String
camelToKababu = fromCamel(val, "-", isUpper)
End Function