Myログ

自分のためのブログ。

csvからjsonに変換するマクロ

csvからjsonに変換するvba
BigQueryのスキーマ定義用のjsonを作成する用に開発。エラーハンドリングなどは仕込んでいない。

Option Explicit

Dim oFSO As Variant

Public Sub Main()

    Dim targetBook As String
    targetBook = GetConfig("定義ファイル")

    Dim book As Workbook
    Set book = OpenBook(targetBook)

    Dim sh As Worksheet
    Set oFSO = CreateObject("Scripting.FileSystemObject")

    For Each sh In book.Worksheets
        readSchemaFromSheet sh
    Next sh

    book.Close

    Set oFSO = Nothing

End Sub

Public Function OpenBook(filename As String)
    Dim buf As String
    Dim book As Workbook
    Dim openedBook As Workbook

    buf = Dir(filename)
    If buf = "" Then
        Set OpenBook = Nothing
        Exit Function
    End If

    For Each book In Workbooks
        If book.name = buf Then
            Set OpenBook = book
            Exit Function
        End If
    Next book

    Application.ScreenUpdating = False
    Set OpenBook = Workbooks.Open(filename)
    Application.ScreenUpdating = True

End Function

Public Function GetConfig(key As String, Optional sheetName = "設定")

    Dim sh As Worksheet
    Dim findValue As String

    Set sh = ThisWorkbook.Worksheets(sheetName)

    findValue = sh.Range("B:B").Find(What:=key).Offset(0, 1).Value

    GetConfig = Trim(findValue)

End Function

Private Function readSchemaFromSheet(sh As Worksheet)

    Dim tableContent As String
    Dim record As String
    Dim no As String
    Dim name As String
    Dim types As String
    Dim mode As String
    Dim line As String

    Dim row As Integer
    row = 2

    tableContent = "["
    Do
        no = sh.Cells(row, 1).Value
        name = sh.Cells(row, 2).Value
        types = convertType(sh.Cells(row, 3).Value)
        mode = sh.Cells(row, 4).Value
        line = ""

        If no = "" Then
            Exit Do
        End If

        line = line + """name"": """ + name + """, ""type"": """ + types + """, ""mode"": """ + mode + """"
        record = "{" + line + "}"

        tableContent = tableContent + record + ","

        row = row + 1

    Loop While no <> ""
    tableContent = Mid(tableContent, 1, Len(tableContent) - 1)
    tableContent = tableContent + "]"

    writeJsonFile sh.name, tableContent

End Function

Private Function writeJsonFile(filename As String, content As String)
    Dim path As String
    Dim fileNo As String
    Dim i As Integer

    path = oFSO.BuildPath(ThisWorkbook.path, filename + ".json")
    fileNo = FreeFile

    Open path For Output As fileNo
    Print #fileNo, content

    Close fileNo

End Function


Private Function convertType(t As String)

    Dim result As String
    Dim wk As String

    wk = Preprocessing(t)

    If wk = "文字列" Then
        convertType = "string"
    ElseIf wk = "数値" Then
        convertType = "integer"
    Else
        '何も変換しない
        convertType = wk
    End If

End Function

Private Function Preprocessing(v As String)
    Preprocessing = Trim(v)
End Function