スネークケースをキャメルケースに変換するスクリプトを紹介する。
スネークケース:
単語と単語をアンダーバーでつなげたもの。
例)sheet_nameキャメルケース:
単語の頭文字を大文字、それ以外の文字を小文字にしてつなげたもの。先頭の単語の頭文字が小文字のものはローワーキャメルケースと言う。
例)sheetNameそうでないものはアッパーキャメルケースと言う。
例)SheetName
アッパーキャメルケースへの変換スクリプト
次の SnakeToUpperCamel 関数は、スネークケースをアッパーキャメルケースに変換する。
''' ''' スネークケースをアッパーキャメルケースに変換します。 ''' Function SnakeToUpperCamel(ByVal snake) SnakeToUpperCamel = "" If Len(snake) = 0 Then Exit Function End If 'アンダーバーで引数を分割する Dim splittedText splittedText = Split(snake, "_") Dim camel camel = "" Dim i For i = LBound(splittedText) To UBound(splittedText) Do Dim txt txt = splittedText(i) If Len(txt) = 0 Then Exit Do End If '単語の先頭を大文字化 Dim ch1st ch1st = UCase(Left(txt, 1)) Dim ch2ndOnwards ch2ndOnwards = "" '単語の2文字目以降を小文字化 If Len(txt) >= 2 Then ch2ndOnwards = LCase(Mid(txt, 2)) End If '変換結果を連結する camel = camel & ch1st & ch2ndOnwards Loop While False Next '変換結果を返す SnakeToUpperCamel = camel End Function
ローワーキャメルケースへの変換スクリプト
次の SnakeToLowerCamel 関数は、スネークケースをローワーキャメルケースに変換する。
''' ''' スネークケースをローワーキャメルケースに変換します。 ''' Function SnakeToLowerCamel(ByVal snake) SnakeToLowerCamel = "" 'いったんアッパーキャメルケースに変換する Dim upperCamel upperCamel = SnakeToUpperCamel(snake) If Len(upperCamel) = 0 Then Exit Function End If '先頭文字だけ小文字にする Dim lowerCamel lowerCamel = LCase(Left(upperCamel, 1)) '2文字目以降はそのまま使う If Len(upperCamel) >= 2 Then lowerCamel = lowerCamel & Mid(upperCamel, 2) End If '変換結果を返す SnakeToLowerCamel = lowerCamel End Function
実行結果
| 引数 | SnakeToLowerCamel | SnakeToUpperCamel |
|---|---|---|
| null | 空文字 | 空文字 |
| 空文字 | 空文字 | 空文字 |
| _ | 空文字 | 空文字 |
| __a_b_c | aBC | ABC |
| A | a | A |
| a | a | A |
| HELLO | hello | Hello |
| hello | hello | Hello |
| HELLO_WORLD | helloWorld | HelloWorld |
| hello_world | helloWorld | HelloWorld |
| あ | あ | あ |
| あいう_えお | あいう_えお | あいう_えお |
| あいう_えお | あいうえお | あいうえお |