🐷

VBAでモダンな文字列操作ができるクラスを作ったよ

に公開

VBA-String2

ダウンロードはこちらから:VBA-String2

はじめに

VBAで文字列操作を行う際、標準の関数では柔軟性に欠けることがあります。JavaScriptのような豊富な文字列メソッドが使えたら、もっと効率的にコーディングできるのに…と感じたことはありませんか?

そこで今回は、VBAでJavaScript風の文字列操作を可能にするカスタムクラス「String2」をご紹介します。オブジェクト指向の考え方を取り入れたこのクラスを使えば、コードの可読性や再利用性が向上し、よりスマートなVBAプログラミングが実現できます。

String2クラスの特徴

JavaScript風のメソッドを多数実装

String2クラスは、JavaScriptのStringオブジェクトに似たメソッドを多数実装しています。例えば:

  • CharAt(index): 指定位置の文字を取得
  • Includes(searchString): 部分文字列の存在を確認
  • IndexOf(searchString): 部分文字列の位置を取得
  • Slice(start, end): 部分文字列を取得
  • ToUpperCase(), ToLowerCase(): 大文字・小文字変換
  • Trim(), TrimStart(), TrimEnd(): 空白の除去
  • Replace(pattern, replacement): 文字列の置換(正規表現対応)
  • Repeat(count): 文字列の繰り返し
  • PadStart(targetLength, padString), PadEnd(targetLength, padString): 文字列のパディング

これらのメソッドにより、VBAでも直感的かつ柔軟な文字列操作が可能になります。

オブジェクト指向による設計

String2クラスは、オブジェクト指向の考え方に基づいて設計されています。クラスモジュールを活用することで、データと処理を一つの単位として管理でき、コードの再利用性や保守性が向上します。

正規表現対応

Match(pattern)Replace(pattern, replacement, useRegex)などのメソッドでは、VBScriptのRegExpオブジェクトを利用して正規表現による文字列操作が可能です。これにより、複雑なパターンマッチングや置換処理も簡潔に記述できます。

利用例

以下は、String2クラスを使った文字列操作の例です。

Sub String2Example()
    Dim result As String2
    Dim i As Long
    Dim arr() As String
    
    ' 1. インスタンスの生成
    Dim s As New String2: s = " Hello, VBA String2! "
    Debug.Print "Original Value: '" & s.Value & "'"   ' Original Value: ' Hello, VBA String2! '
    
    ' 2. length プロパティ
    Debug.Print "Length: "; s.length                                       ' Length: 21
    
    ' 3. CharAt / CharCodeAt
    Set result = s.CharAt(1)
    Debug.Print "CharAt(1): '" & result.Value & "'"                 ' CharAt(1): 'H'
    Debug.Print "CharCodeAt(1): "; s.CharCodeAt(1)                     ' CharCodeAt(1): 72
    
    ' 4. Concat
    Set result = s.Concat(" Enjoy!")
    Debug.Print "Concat: '" & result.Value & "'"                    ' Concat: ' Hello, VBA String2!  Enjoy!'
    
    ' 5. EndsWith / StartsWith / Includes
    Debug.Print "EndsWith(""! ""): "; s.EndsWith("! ")          ' EndsWith("! "): True
    Debug.Print "StartsWith("" ""): "; s.StartsWith(" ")      ' StartsWith(" "): True
    Debug.Print "Includes(""VBA""): "; s.Includes("VBA")      ' Includes("VBA"): True
    
    ' 6. IndexOf / LastIndexOf
    Debug.Print "IndexOf(""a""): "; s.IndexOf("a")            ' IndexOf("a"): 8
    Debug.Print "LastIndexOf(""a""): "; s.LastIndexOf("a")  ' LastIndexOf("a"): 15
    
    ' 7. Match (正規表現で単語を抽出)
    arr = s.Match("\w+")
    If Not IsNull(arr) Then
        Debug.Print "Match \w+:";
        For i = LBound(arr) To UBound(arr)
            Debug.Print " [" & arr(i) & "]"                           ' [Hello] [VBA] [String2]
        Next i
    End If
    
    ' 8. PadEnd / PadStart
    Debug.Print "PadEnd(30, ""-"" ): '" & s.PadEnd(30, "-").Value & "'"   ' PadEnd(30, "-"): ' Hello, VBA String2! -------'
    Debug.Print "PadStart(30, ""-"" ): '" & s.PadStart(30, "-").Value & "'" ' PadStart(30, "-"): '------- Hello, VBA String2! '
    
    ' 9. Repeat
    Debug.Print "Repeat(2): '" & s.NewInstance("AB").Repeat(2).Value & "'"    ' Repeat(2): 'ABAB'
    
    ' 10. Replace / ReplaceAll
    Debug.Print "Replace(""VBA"", ""VBScript""): '" & s.Replace("VBA", "VBScript").Value & "'"  ' Replace: ' Hello, VBScript String2! '
    Debug.Print "ReplaceAll("" "", ""_""): '" & s.ReplaceAll(" ", "_").Value & "'"      ' ReplaceAll: '_Hello,_VBA_String2!_'
    
    ' 11. Reverse
    Debug.Print "Reverse: '" & s.Reverse().Value & "'"                    ' Reverse: '!2gnirtS ABV ,olleH '
    
    ' 12. Search (正規表現で「String2」を検索)
    Debug.Print "Search(""String2""): "; s.Search("String2")         ' Search("String2"): 12
    
    ' 13. Slice / SubString
    Debug.Print "Slice(1,5): '" & s.Slice(1, 5).Value & "'"      ' Slice(1,5): 'Hello'
    Debug.Print "SubString(1,5): '" & s.SubString(1, 5).Value & "'" ' SubString(1,5): 'ello,'
    
    ' 14. Split
    arr = s.Split(",")
    Debug.Print "Split by comma:";
    For i = LBound(arr) To UBound(arr)
        Debug.Print "  Part[" & i & "]: '" & arr(i) & "'"         ' Part[0]: ' Hello' / Part[1]: ' VBA String2! '
    Next i
    
    ' 15. ToCharArray
    arr = s.ToCharArray()
    Debug.Print "ToCharArray:";
    For i = LBound(arr) To UBound(arr)
        Debug.Print "  [" & i & "]=" & arr(i)                      ' 各文字を一つずつ表示
    Next i
    
    ' 16. ToLowerCase / ToUpperCase
    Debug.Print "ToLowerCase: '" & s.ToLowerCase().Value & "'"    ' ToLowerCase: ' hello, vba string2! '
    Debug.Print "ToUpperCase: '" & s.ToUpperCase().Value & "'"    ' ToUpperCase: ' HELLO, VBA STRING2! '
    
    ' 17. Trim系
    Debug.Print "Trim: '" & s.Trim().Value & "'"              ' Trim: 'Hello, VBA String2!'
    Debug.Print "TrimStart: '" & s.TrimStart().Value & "'"    ' TrimStart: 'Hello, VBA String2! '
    Debug.Print "TrimEnd: '" & s.TrimEnd().Value & "'"        ' TrimEnd: ' Hello, VBA String2!'
End Sub

このように、String2クラスを使えば、VBAでも洗練された文字列操作が可能になります。

まとめ

String2クラスは、VBAでの文字列操作をより直感的かつ柔軟にするための強力なツールです。JavaScript風のメソッドを多数実装し、正規表現にも対応しているため、複雑な文字列処理も簡潔に記述できます。

VBAでの開発効率を高めたい方や、よりモダンなコーディングスタイルを取り入れたい方は、ぜひString2クラスを活用してみてください。

Discussion