Sub CreateInsertSQL()
Dim ws As Worksheet
Dim tableName As String
Dim colNames As String
Dim rowCount As Long
Dim colCount As Long
Dim i As Long, j As Long
Dim insertSQL As String
Dim fileName As String
Dim fileNum As Integer
Dim filePath As String
Dim nn As Integer
Dim fileExists As Boolean
Set ws = ThisWorkbook.Sheets("Sheet1") ' シート名を適宜変更してください
' テーブル名を取得
tableName = ws.Range("B1").Value
' カラム名を取得
colCount = ws.Cells(3, ws.Columns.Count).End(xlToLeft).Column
colNames = ""
For j = 1 To colCount
colNames = colNames & ws.Cells(3, j).Value
If j <> colCount Then
colNames = colNames & ", "
End If
Next j
' 行数を取得
rowCount = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
' INSERT文を作成
insertSQL = ""
For i = 4 To rowCount
insertSQL = insertSQL & "INSERT INTO " & tableName & " (" & colNames & ") VALUES ("
For j = 1 To colCount
' 値が数値の場合
If IsNumeric(ws.Cells(i, j).Value) And Not IsEmpty(ws.Cells(i, j).Value) Then
insertSQL = insertSQL & ws.Cells(i, j).Value
' 値が日付の場合
'ElseIf IsDate(ws.Cells(i, j).Value) Then
' insertSQL = insertSQL & "'" & Format(ws.Cells(i, j).Value, "yyyy-mm-dd") & "'"
' 値が文字列の場合
Else
insertSQL = insertSQL & "'" & Replace(ws.Cells(i, j).Value, "'", "''") & "'"
End If
If j <> colCount Then
insertSQL = insertSQL & ", "
End If
Next j
insertSQL = insertSQL & ");" & vbCrLf
Next i
' ファイル名を作成
nn = 1
Do
fileName = "insert_" & tableName & "_" & Format(nn, "00") & ".sql"
filePath = ThisWorkbook.Path & Application.PathSeparator & fileName
If Dir(filePath) <> "" Then
nn = nn + 1
Else
Exit Do
End If
Loop
' ファイルに書き込み
fileNum = FreeFile
Open filePath For Output As #fileNum
Print #fileNum, insertSQL
Close #fileNum
MsgBox "INSERT文をファイルに出力しました: " & fileName
End Sub
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme