LoginSignup
0
0

More than 1 year has passed since last update.

VBAでCSVからINSERT SQLを作成する方法

Posted at

CSVと書いてありますがExcelから作ります。
シート名がテーブル名となります。

Sub ConvertToInsertStatements()
    Dim ws As Worksheet
    Dim outputWs As Worksheet
    Dim tableName As String
    Dim r As Long, c As Long
    Dim insertStmt As String
    Dim values As String

    ' 現在のアクティブなシートを処理対象とします
    Set ws = ActiveSheet

    ' 出力用の新しいシートを作成します
    Set outputWs = Worksheets.Add
    outputWs.Name = "InsertStatements"

    ' テーブル名をシート名から取得します
    tableName = ws.Name

    ' 1行目からカラム名を取得し、インサート文の基本形を作成します
    insertStmt = "INSERT INTO " & tableName & " ("
    For c = 1 To ws.Cells(1, Columns.Count).End(xlToLeft).Column
        insertStmt = insertStmt & ws.Cells(1, c).Value
        If c < ws.Cells(1, Columns.Count).End(xlToLeft).Column Then
            insertStmt = insertStmt & ", "
        End If
    Next c
    insertStmt = insertStmt & ") VALUES "

    ' 2行目以降のデータ行を処理し、インサート文を生成します
    For r = 2 To ws.Cells(Rows.Count, 1).End(xlUp).Row
        values = "("
        For c = 1 To ws.Cells(1, Columns.Count).End(xlToLeft).Column
            If IsNumeric(ws.Cells(r, c).Value) Then
                values = values & ws.Cells(r, c).Value
            Else
                values = values & "'" & ws.Cells(r, c).Value & "'"
            End If

            If c < ws.Cells(1, Columns.Count).End(xlToLeft).Column Then
                values = values & ", "
            End If
        Next c
        values = values & ");"

        ' インサート文を出力シートに書き込みます
        outputWs.Cells(r - 1, 1).Value = insertStmt & values
    Next r

    MsgBox "インサート文の生成が完了しました。", vbInformation
End Sub
0
0
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
0
0