LoginSignup
2
3

More than 3 years have passed since last update.

[VBA] CSV 文字列を二次元配列に変換する

Last updated at Posted at 2018-10-19

はじめに

CSV 文字列を(ワークシートに書き込むためなどで)二次元配列に変換したいことはよくあります。

私は別の仕組みで CSV 文字列を作り、Excel とやり取りしています。

データ自体にカンマが含まれることは多々あるので、区切り文字は任意のものに簡単に置き換えできることが望ましいです。

また、WorksheetFunction.Transpose() を使ってワークシートに書き込むことも多いため行列入れ替えた形で二次元配列に初期化したいことが、しばしばあります。

このような要件から、自分の使いやすいように変換関数を作成しました。

スニペット

' -----
' CSV を分解して二次元配列にして返す。
' 引数  :csvText                二次元配列に変換したい CSV 文字列
'       :recSep                 レコード区切りの文字。既定値は vbCrLf。
'       :fldSep                 フィールドの区切り文字。既定値は ","。
'       :swapRowColumn          行と列を入れ替えるかの真偽値。既定値は False。
' 返値  :二次元配列
' https://qiita.com/Tachy_Pochy/items/89cc44237f872a2d9f09
' -----
Public Function CSV2Array(csvText As String, _
                          Optional recSep As String = vbCrLf, _
                          Optional fldSep As String = ",", _
                          Optional swapRowColumn As Boolean = False) As Variant
    Dim ret As Variant
    Dim lines As Variant
    lines = Split(csvText, recSep)

    If UBound(lines) <= 0 Then GoTo EmptyExit

    Dim flds As Variant
    flds = Split(lines(LBound(lines)), fldSep)
    If swapRowColumn Then
        ReDim ret(LBound(flds) To UBound(flds), LBound(lines) To UBound(lines)) As String
    Else
        ReDim ret(LBound(lines) To UBound(lines), LBound(flds) To UBound(flds)) As String
    End If

    On Error GoTo ErrorExit

    Dim r As Integer, c As Integer
    Dim fields As Variant
    For r = LBound(lines) To UBound(lines)
        If Trim(lines(r)) <> "" Then
            fields = Split(lines(r), fldSep)
            For c = LBound(flds) To UBound(flds) ' 1行目のフィールド数を使用し、各行でまちまちにならないようにする。
                If swapRowColumn Then
                    ret(c, r) = fields(c)
                Else
                    ret(r, c) = fields(c)
                End If
            Next
        End If
    Next

    CSV2Array = ret
    Exit Function
ErrorExit:
    Debug.Print r, c, lines(r)
    MsgBoxEx Err.Description
    Exit Function
EmptyExit:
    ret = Array()
    CSV2Array = ret
End Function
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3